
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>re --- 正则表达式操作 &#8212; Python 3.7.3 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.3 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="模块 difflib 是一个计算差异的助手" href="difflib.html" />
    <link rel="prev" title="string --- 常见的字符串操作" href="string.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/re.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/switchers.js"></script>
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="difflib.html" title="模块 difflib 是一个计算差异的助手"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="string.html" title="string --- 常见的字符串操作"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">zh_CN</span>
          <span class="version_switcher_placeholder">3.7.3</span>
          <a href="../index.html">文档</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="text.html" accesskey="U">文本处理服务</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-re">
<span id="re-regular-expression-operations"></span><h1><a class="reference internal" href="#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> --- 正则表达式操作<a class="headerlink" href="#module-re" title="永久链接至标题">¶</a></h1>
<p><strong>源代码:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/re.py">Lib/re.py</a></p>
<hr class="docutils" />
<p>这个模块提供了与 Perl 语言类似的正则表达式匹配操作。</p>
<p>要搜索的样式和字符串可以是 Unicode 字符串 (<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>) 以及8位字节串 (<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>)。 但是，Unicode 字符串与8位字节串不能混用：也就是说，你不能用一个字节串样式去匹配 Unicode 字符串，反之亦然；类似地，当进行替换操作时，替换字符串必须与所用的样式和搜索字符串都为相同类型。</p>
<p>正则表达式使用反斜框字符 (<code class="docutils literal notranslate"><span class="pre">'\'</span></code>) 来提示特殊形式或是允许使用特殊字符而又不启用它们的特殊含义。 这会与 Python 在字符串字面值中出于相同目的而使用的相同字符发生冲突；例如，为了匹配一个反斜杠字面值，样式字符串就需要写成 <code class="docutils literal notranslate"><span class="pre">'\\\\'</span></code>，因为正则表达式必须写成 <code class="docutils literal notranslate"><span class="pre">\\</span></code>，而每个反斜杠在普通的 Python 字符串字面值内又必须写成 <code class="docutils literal notranslate"><span class="pre">\\</span></code>。</p>
<p>解决办法是对于正则表达式样式使用 Python 的原始字符串表示法；在带有 <code class="docutils literal notranslate"><span class="pre">'r'</span></code> 前缀的字符串字面值中，反斜杠不必做任何特殊处理。 因此 <code class="docutils literal notranslate"><span class="pre">r&quot;\n&quot;</span></code> 表示包含 <code class="docutils literal notranslate"><span class="pre">'\'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'n'</span></code> 两个字符的字符串，而 <code class="docutils literal notranslate"><span class="pre">&quot;\n&quot;</span></code> 则表示只包含一个换行符的字符串。 样式在 Python 代码中通常都会使用这种原始字符串表示法来表示。</p>
<p>绝大部分正则表达式操作都提供为模块函数和方法，在 <a class="reference internal" href="#re-objects"><span class="std std-ref">编译正则表达式</span></a>.  这些函数是一个捷径，不需要先编译一个正则对象，但是损失了一些优化参数。</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">第三方模块 <a class="reference external" href="https://pypi.org/project/regex/">regex</a> , 提供了与标准库 <a class="reference internal" href="#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> 模块兼容的API接口, 同时还提供了额外的功能和更全面的Unicode支持。</p>
</div>
<div class="section" id="regular-expression-syntax">
<span id="re-syntax"></span><h2>正则表达式语法<a class="headerlink" href="#regular-expression-syntax" title="永久链接至标题">¶</a></h2>
<p>一个正则表达式（或RE）指定了一集与之匹配的字符串；模块内的函数可以让你检查某个字符串是否跟给定的正则表达式匹配（或者一个正则表达式是否匹配到一个字符串，这两种说法含义相同）。</p>
<p>正则表达式可以拼接； 如果 <em>A</em> 和 <em>B</em> 都是正则表达式， 那么 <em>AB</em> 也是正则表达式。 通常， 如果字符串 <em>p</em> 匹配 <em>A</em> 并且另一个字符串 <em>q</em> 匹配 <em>B</em>, 那么 <em>pq</em> 可以匹配 AB。除非 <em>A</em> 或者 <em>B</em> 包含低优先级操作，<em>A</em> 和 <em>B</em> 存在边界条件；或者命名组引用。所以，复杂表达式可以很容易的从这里描述的简单源语表达式构建。 了解更多正则表达式理论和实现，参考the Friedl book <a class="reference internal" href="#frie09" id="id1">[Frie09]</a> ，或者其他编译器构建的书籍。</p>
<p>以下是正则表达式格式的简要说明。更详细的信息和演示，参考  <a class="reference internal" href="../howto/regex.html#regex-howto"><span class="std std-ref">正则表达式HOWTO</span></a>。</p>
<p>正则表达式可以包含普通或者特殊字符。绝大部分普通字符，比如 <code class="docutils literal notranslate"><span class="pre">'A'</span></code>, <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, 或者 <code class="docutils literal notranslate"><span class="pre">'0'</span></code>，都是最简单的正则表达式。它们就匹配自身。你可以拼接普通字符，所以 <code class="docutils literal notranslate"><span class="pre">last</span></code> 匹配字符串 <code class="docutils literal notranslate"><span class="pre">'last'</span></code>.  （在这一节的其他部分，我们将用 <code class="docutils literal notranslate"><span class="pre">this</span> <span class="pre">special</span> <span class="pre">style</span></code> 这种方式表示正则表达式，通常不带引号，要匹配的字符串用 <code class="docutils literal notranslate"><span class="pre">'in</span> <span class="pre">single</span> <span class="pre">quotes'</span></code> ，单引号形式。）</p>
<p>有些字符，比如 <code class="docutils literal notranslate"><span class="pre">'|'</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">'('</span></code>，属于特殊字符。 特殊字符既可以表示它的普通含义， 也可以影响它旁边的正则表达式的解释。</p>
<p>重复修饰符 (<code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">?</span></code>, <code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>, 等) 不能直接嵌套。这样避免了非贪婪后缀 <code class="docutils literal notranslate"><span class="pre">?</span></code> 修饰符，和其他实现中的修饰符产生的多义性。要应用一个内层重复嵌套，可以使用括号。 比如，表达式 <code class="docutils literal notranslate"><span class="pre">(?:a{6})*</span></code> 匹配6个 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> 字符重复任意次数。</p>
<p>特殊字符是：</p>
<dl class="docutils" id="index-0">
<dt><code class="docutils literal notranslate"><span class="pre">.</span></code></dt>
<dd>(点) 在默认模式，匹配除了换行的任意字符。如果指定了标签 <a class="reference internal" href="#re.DOTALL" title="re.DOTALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">DOTALL</span></code></a> ，它将匹配包括换行符的任意字符。</dd>
</dl>
<dl class="docutils" id="index-1">
<dt><code class="docutils literal notranslate"><span class="pre">^</span></code></dt>
<dd>(插入符号)  匹配字符串的开头， 并且在 <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> 模式也匹配换行后的首个符号。</dd>
</dl>
<dl class="docutils" id="index-2">
<dt><code class="docutils literal notranslate"><span class="pre">$</span></code></dt>
<dd>匹配字符串尾或者换行符的前一个字符，在 <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> 模式匹配换行符的前一个字符。  <code class="docutils literal notranslate"><span class="pre">foo</span></code> 匹配 <code class="docutils literal notranslate"><span class="pre">'foo'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'foobar'</span></code> , 但正则 <code class="docutils literal notranslate"><span class="pre">foo$</span></code> 只匹配 <code class="docutils literal notranslate"><span class="pre">'foo'</span></code>。更有趣的是， 在 <code class="docutils literal notranslate"><span class="pre">'foo1\nfoo2\n'</span></code> 搜索 <code class="docutils literal notranslate"><span class="pre">foo.$</span></code> ，通常匹配  <code class="docutils literal notranslate"><span class="pre">'foo2'</span></code> ，但在 <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> 模式 ，可以匹配到 <code class="docutils literal notranslate"><span class="pre">'foo1'</span></code> ；在 <code class="docutils literal notranslate"><span class="pre">'foo\n'</span></code> 搜索 <code class="docutils literal notranslate"><span class="pre">$</span></code> 会找到两个空串：一个在换行前，一个在字符串最后。</dd>
</dl>
<dl class="docutils" id="index-3">
<dt><code class="docutils literal notranslate"><span class="pre">*</span></code></dt>
<dd>对它前面的正则式匹配0到任意次重复， 尽量多的匹配字符串。  <code class="docutils literal notranslate"><span class="pre">ab*</span></code> 会匹配 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>， <code class="docutils literal notranslate"><span class="pre">'ab'</span></code>， 或者 <code class="docutils literal notranslate"><span class="pre">'a'``后面跟随任意个</span> <span class="pre">``'b'</span></code>。</dd>
</dl>
<dl class="docutils" id="index-4">
<dt><code class="docutils literal notranslate"><span class="pre">+</span></code></dt>
<dd>对它前面的正则式匹配1到任意次重复。 <code class="docutils literal notranslate"><span class="pre">ab+</span></code> 会匹配 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> 后面跟随1个以上到任意个 <code class="docutils literal notranslate"><span class="pre">'b'</span></code>，它不会匹配 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>。</dd>
</dl>
<dl class="docutils" id="index-5">
<dt><code class="docutils literal notranslate"><span class="pre">?</span></code></dt>
<dd>对它前面的正则式匹配0到1次重复。 <code class="docutils literal notranslate"><span class="pre">ab?</span></code> 会匹配 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">'ab'</span></code>。</dd>
</dl>
<dl class="docutils" id="index-6">
<dt><code class="docutils literal notranslate"><span class="pre">*?</span></code>, <code class="docutils literal notranslate"><span class="pre">+?</span></code>, <code class="docutils literal notranslate"><span class="pre">??</span></code></dt>
<dd><code class="docutils literal notranslate"><span class="pre">'*'</span></code>, <code class="docutils literal notranslate"><span class="pre">'+'</span></code>，和 <code class="docutils literal notranslate"><span class="pre">'?'</span></code> 修饰符都是 <em class="dfn">贪婪的</em>；它们在字符串进行尽可能多的匹配。有时候并不需要这种行为。如果正则式 <code class="docutils literal notranslate"><span class="pre">&lt;.*&gt;</span></code> 希望找到 <code class="docutils literal notranslate"><span class="pre">'&lt;a&gt;</span> <span class="pre">b</span> <span class="pre">&lt;c&gt;'</span></code>，它将会匹配整个字符串，而不仅是 <code class="docutils literal notranslate"><span class="pre">'&lt;a&gt;'</span></code>。在修饰符之后添加 <code class="docutils literal notranslate"><span class="pre">?</span></code> 将使样式以 <em class="dfn">非贪婪`方式或者 :dfn:`最小</em> 方式进行匹配； 尽量 <em>少</em> 的字符将会被匹配。 使用正则式 <code class="docutils literal notranslate"><span class="pre">&lt;.*?&gt;</span></code> 将会仅仅匹配 <code class="docutils literal notranslate"><span class="pre">'&lt;a&gt;'</span></code>。</dd>
</dl>
<dl class="docutils" id="index-7">
<dt>&quot;{m}&quot;</dt>
<dd>对其之前的正则式指定匹配 <em>m</em> 个重复；少于 <em>m</em> 的话就会导致匹配失败。比如， <code class="docutils literal notranslate"><span class="pre">a{6}</span></code> 将匹配6个 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> , 但是不能是5个。</dd>
<dt>&quot;{m, n}&quot;</dt>
<dd>对正则式进行 <em>m</em> 到 <em>n</em> 次匹配，在 <em>m</em> 和 <em>n</em> 之间取尽量多。 比如，<code class="docutils literal notranslate"><span class="pre">a{3,5}</span></code> 将匹配 3 到 5个 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>。忽略 <em>m</em> 意为指定下界为0，忽略 <em>n</em> 指定上界为无限次。 比如 <code class="docutils literal notranslate"><span class="pre">a{4,}b</span></code> 将匹配 <code class="docutils literal notranslate"><span class="pre">'aaaab'</span></code> 或者1000个 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> 尾随一个 <code class="docutils literal notranslate"><span class="pre">'b'</span></code>，但不能匹配 <code class="docutils literal notranslate"><span class="pre">'aaab'</span></code>。逗号不能省略，否则无法辨别修饰符应该忽略哪个边界。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">{m,n}?</span></code></dt>
<dd>前一个修饰符的非贪婪模式，只匹配尽量少的字符次数。比如，对于 <code class="docutils literal notranslate"><span class="pre">'aaaaaa'</span></code>， <code class="docutils literal notranslate"><span class="pre">a{3,5}</span></code> 匹配 5个 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> ，而 <code class="docutils literal notranslate"><span class="pre">a{3,5}?</span></code> 只匹配3个 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>。</dd>
</dl>
<dl class="docutils" id="index-8">
<dt><code class="docutils literal notranslate"><span class="pre">\</span></code></dt>
<dd><p class="first">转义特殊字符（允许你匹配 <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, <code class="docutils literal notranslate"><span class="pre">'?'</span></code>, 或者此类其他），或者表示一个特殊序列；特殊序列之后进行讨论。</p>
<p class="last">如果你没有使用原始字符串（ <code class="docutils literal notranslate"><span class="pre">r'raw'</span></code> ）来表达样式，要牢记Python也使用反斜杠作为转义序列；如果转义序列不被Python的分析器识别，反斜杠和字符才能出现在字符串中。如果Python可以识别这个序列，那么反斜杠就应该重复两次。这将导致理解障碍，所以高度推荐，就算是最简单的表达式，也要使用原始字符串。</p>
</dd>
</dl>
<dl class="docutils" id="index-9">
<dt><code class="docutils literal notranslate"><span class="pre">[]</span></code></dt>
<dd><p class="first">用于表示一个字符集合。在一个集合中：</p>
<ul class="simple">
<li>字符可以单独列出，比如 <code class="docutils literal notranslate"><span class="pre">[amk]</span></code> 匹配 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>， <code class="docutils literal notranslate"><span class="pre">'m'</span></code>， 或者 <code class="docutils literal notranslate"><span class="pre">'k'</span></code>。</li>
</ul>
<ul class="simple" id="index-10">
<li>可以表示字符范围，通过用 <code class="docutils literal notranslate"><span class="pre">'-'</span></code> 将两个字符连起来。比如 <code class="docutils literal notranslate"><span class="pre">[a-z]</span></code> 将匹配任何小写ASCII字符， <code class="docutils literal notranslate"><span class="pre">[0-5][0-9]</span></code> 将匹配从 <code class="docutils literal notranslate"><span class="pre">00</span></code> 到 <code class="docutils literal notranslate"><span class="pre">59</span></code> 的两位数字， <code class="docutils literal notranslate"><span class="pre">[0-9A-Fa-f]</span></code> 将匹配任何十六进制数位。 如果 <code class="docutils literal notranslate"><span class="pre">-</span></code> 进行了转义 （比如 <code class="docutils literal notranslate"><span class="pre">[a\-z]</span></code>）或者它的位置在首位或者末尾（如 <code class="docutils literal notranslate"><span class="pre">[-a]</span></code> 或 <code class="docutils literal notranslate"><span class="pre">[a-]</span></code>），它就只表示普通字符 <code class="docutils literal notranslate"><span class="pre">'-'</span></code>。</li>
<li>特殊字符在集合中，失去它的特殊含义。比如 <code class="docutils literal notranslate"><span class="pre">[(+*)]</span></code> 只会匹配这几个文法字符 <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">'+'</span></code>, <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, or <code class="docutils literal notranslate"><span class="pre">')'</span></code>。</li>
</ul>
<ul class="simple" id="index-11">
<li>字符类如 <code class="docutils literal notranslate"><span class="pre">\w</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">\S</span></code> (如下定义) 在集合内可以接受，它们可以匹配的字符由 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 或者 <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> 模式决定。</li>
</ul>
<ul class="simple" id="index-12">
<li>不在集合范围内的字符可以通过 <em class="dfn">取反</em> 来进行匹配。如果集合首字符是 <code class="docutils literal notranslate"><span class="pre">'^'</span></code> ，所有 <em>不</em> 在集合内的字符将会被匹配，比如 <code class="docutils literal notranslate"><span class="pre">[^5]</span></code> 将匹配所有字符，除了 <code class="docutils literal notranslate"><span class="pre">'5'</span></code>， <code class="docutils literal notranslate"><span class="pre">[^^]</span></code> 将匹配所有字符，除了 <code class="docutils literal notranslate"><span class="pre">'^'</span></code>.  <code class="docutils literal notranslate"><span class="pre">^</span></code> 如果不在集合首位，就没有特殊含义。</li>
<li>在集合内要匹配一个字符 <code class="docutils literal notranslate"><span class="pre">']'</span></code>，有两种方法，要么就在它之前加上反斜杠，要么就把它放到集合首位。比如， <code class="docutils literal notranslate"><span class="pre">[()[\]{}]</span></code> 和 <code class="docutils literal notranslate"><span class="pre">[]()[{}]</span></code> 都可以匹配括号。</li>
</ul>
<ul class="simple">
<li><a class="reference external" href="https://unicode.org/reports/tr18/">Unicode Technical Standard #18</a> 里的嵌套集合和集合操作支持可能在未来添加。这将会改变语法，所以为了帮助这个改变，一个 <a class="reference internal" href="exceptions.html#FutureWarning" title="FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a> 将会在有多义的情况里被 <code class="docutils literal notranslate"><span class="pre">raise</span></code>，包含以下几种情况，集合由 <code class="docutils literal notranslate"><span class="pre">'['</span></code> 开始，或者包含下列字符序列  <code class="docutils literal notranslate"><span class="pre">'--'</span></code>, <code class="docutils literal notranslate"><span class="pre">'&amp;&amp;'</span></code>, <code class="docutils literal notranslate"><span class="pre">'~~'</span></code>, 和 <code class="docutils literal notranslate"><span class="pre">'||'</span></code>。为了避免警告，需要将它们用反斜杠转义。</li>
</ul>
<div class="last versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>如果一个字符串构建的语义在未来会改变的话，一个 <a class="reference internal" href="exceptions.html#FutureWarning" title="FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a> 会 <code class="docutils literal notranslate"><span class="pre">raise</span></code> 。</p>
</div>
</dd>
</dl>
<dl class="docutils" id="index-13">
<dt><code class="docutils literal notranslate"><span class="pre">|</span></code></dt>
<dd><code class="docutils literal notranslate"><span class="pre">A|B</span></code>， <em>A</em> 和 <em>B</em> 可以是任意正则表达式，创建一个正则表达式，匹配 <em>A</em> 或者 <em>B</em>.  任意个正则表达式可以用 <code class="docutils literal notranslate"><span class="pre">'|'</span></code> 连接。它也可以在组合（见下列）内使用。扫描目标字符串时， <code class="docutils literal notranslate"><span class="pre">'|'</span></code> 分隔开的正则样式从左到右进行匹配。当一个样式完全匹配时，这个分支就被接受。意思就是，一旦 <em>A</em> 匹配成功， <em>B</em> 就不再进行匹配，即便它能产生一个更好的匹配。或者说，<code class="docutils literal notranslate"><span class="pre">'|'</span></code> 操作符绝不贪婪。  如果要匹配 <code class="docutils literal notranslate"><span class="pre">'|'</span></code> 字符，使用 <code class="docutils literal notranslate"><span class="pre">\|</span></code>， 或者把它包含在字符集里，比如 <code class="docutils literal notranslate"><span class="pre">[|]</span></code>.</dd>
</dl>
<dl class="docutils" id="index-14">
<dt><code class="docutils literal notranslate"><span class="pre">(...)</span></code></dt>
<dd>（组合），匹配括号内的任意正则表达式，并标识出组合的开始和结尾。匹配完成后，组合的内容可以被获取，并可以在之后用  <code class="docutils literal notranslate"><span class="pre">\number</span></code> 转义序列进行再次匹配，之后进行详细说明。要匹配字符 <code class="docutils literal notranslate"><span class="pre">'('</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">')'</span></code>, 用 <code class="docutils literal notranslate"><span class="pre">\(</span></code> 或 <code class="docutils literal notranslate"><span class="pre">\)</span></code>, 或者把它们包含在字符集合里: <code class="docutils literal notranslate"><span class="pre">[(]</span></code>, <code class="docutils literal notranslate"><span class="pre">[)]</span></code>.</dd>
</dl>
<dl class="docutils" id="index-15">
<dt><code class="docutils literal notranslate"><span class="pre">(?…)</span></code></dt>
<dd>这是个扩展标记法 （一个 <code class="docutils literal notranslate"><span class="pre">'?'</span></code> 跟随 <code class="docutils literal notranslate"><span class="pre">'('</span></code> 并无含义）。  <code class="docutils literal notranslate"><span class="pre">'?'</span></code> 后面的第一个字符决定了这个构建采用什么样的语法。这种扩展通常并不创建新的组合； <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code> 是唯一的例外。 以下是目前支持的扩展。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?aiLmsux)</span></code></dt>
<dd>( <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'i'</span></code>, <code class="docutils literal notranslate"><span class="pre">'L'</span></code>, <code class="docutils literal notranslate"><span class="pre">'m'</span></code>, <code class="docutils literal notranslate"><span class="pre">'s'</span></code>, <code class="docutils literal notranslate"><span class="pre">'u'</span></code>, <code class="docutils literal notranslate"><span class="pre">'x'</span></code> 中的一个或多个) 这个组合匹配一个空字符串；这些字符对正则表达式设置以下标记 <a class="reference internal" href="#re.A" title="re.A"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.A</span></code></a> (只匹配ASCII字符), <a class="reference internal" href="#re.I" title="re.I"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.I</span></code></a> (忽略大小写), <a class="reference internal" href="#re.L" title="re.L"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.L</span></code></a> (语言依赖), <a class="reference internal" href="#re.M" title="re.M"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.M</span></code></a> (多行模式), <a class="reference internal" href="#re.S" title="re.S"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.S</span></code></a> (点dot匹配全部字符), <code class="xref py py-const docutils literal notranslate"><span class="pre">re.U</span></code> (Unicode匹配), and <a class="reference internal" href="#re.X" title="re.X"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.X</span></code></a> (冗长模式)。 (这些标记在 <a class="reference internal" href="#contents-of-module-re"><span class="std std-ref">模块内容</span></a> 中描述) 如果你想将这些标记包含在正则表达式中，这个方法就很有用，免去了在 <a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> 中传递 <em>flag</em> 参数。标记应该在表达式字符串首位表示。</dd>
</dl>
<dl class="docutils" id="index-16">
<dt><code class="docutils literal notranslate"><span class="pre">(?:…)</span></code></dt>
<dd>正则括号的非捕获版本。只识别，不取值。匹配在括号内的任何正则式，但匹配完成后，这个子串不做为结果被获取。比如 <code class="docutils literal notranslate"><span class="pre">(?:a)bc</span></code> 指定了匹配样式 <code class="docutils literal notranslate"><span class="pre">bc</span></code>，但这个样式前面必须是字符 <code class="docutils literal notranslate"><span class="pre">a</span></code>，它可以匹配 <code class="docutils literal notranslate"><span class="pre">'abc'</span></code>，但不能匹配 <code class="docutils literal notranslate"><span class="pre">'bbc'</span></code>，匹配完成后只返回 <code class="docutils literal notranslate"><span class="pre">'bc'</span></code> 作为匹配内容。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?aiLmsux-imsx:…)</span></code></dt>
<dd><p class="first">(<code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'i'</span></code>, <code class="docutils literal notranslate"><span class="pre">'L'</span></code>, <code class="docutils literal notranslate"><span class="pre">'m'</span></code>, <code class="docutils literal notranslate"><span class="pre">'s'</span></code>, <code class="docutils literal notranslate"><span class="pre">'u'</span></code>, <code class="docutils literal notranslate"><span class="pre">'x'</span></code> 中的0或者多个， 之后可选跟随 <code class="docutils literal notranslate"><span class="pre">'-'</span></code> 在后面跟随 <code class="docutils literal notranslate"><span class="pre">'i'</span></code> , <code class="docutils literal notranslate"><span class="pre">'m'</span></code> , <code class="docutils literal notranslate"><span class="pre">'s'</span></code> , <code class="docutils literal notranslate"><span class="pre">'x'</span></code> 中的一到多个 .) 这些字符为表达式的其中一部分 <em>设置</em> 或者 <em>去除</em> 相应标记 <a class="reference internal" href="#re.A" title="re.A"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.A</span></code></a> (只匹配ASCII), <a class="reference internal" href="#re.I" title="re.I"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.I</span></code></a> (忽略大小写), <a class="reference internal" href="#re.L" title="re.L"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.L</span></code></a> (语言依赖), <a class="reference internal" href="#re.M" title="re.M"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.M</span></code></a> (多行), <a class="reference internal" href="#re.S" title="re.S"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.S</span></code></a> (点匹配所有字符), <code class="xref py py-const docutils literal notranslate"><span class="pre">re.U</span></code> (Unicode匹配), and <a class="reference internal" href="#re.X" title="re.X"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.X</span></code></a> (冗长模式)。(标记描述在 <a class="reference internal" href="#contents-of-module-re"><span class="std std-ref">模块内容</span></a> .)</p>
<p><code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'L'</span></code> and <code class="docutils literal notranslate"><span class="pre">'u'</span></code> 作为内联标记是相互排斥的， 所以它们不能结合在一起，或者跟随 <code class="docutils literal notranslate"><span class="pre">'-'</span></code> 。 当他们中的某个出现在内联组中，它就覆盖了括号组内的匹配模式。在Unicode样式中， <code class="docutils literal notranslate"><span class="pre">(?a:...)</span></code> 切换为 只匹配ASCII， <code class="docutils literal notranslate"><span class="pre">(?u:...)</span></code> 切换为Unicode匹配 (默认).  在byte样式中 <code class="docutils literal notranslate"><span class="pre">(?L:...)</span></code> 切换为语言依赖模式， <code class="docutils literal notranslate"><span class="pre">(?a:...)</span></code> 切换为 只匹配ASCII (默认)。这种方式只覆盖组合内匹配，括号外的匹配模式不受影响。</p>
<div class="versionadded">
<p><span class="versionmodified">3.6 新版功能.</span></p>
</div>
<div class="last versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>符号 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'L'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'u'</span></code> 同样可以用在一个组合内。</p>
</div>
</dd>
</dl>
<dl class="docutils" id="index-17">
<dt><code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;…)</span></code></dt>
<dd><p class="first">（命名组合）类似正则组合，但是匹配到的子串组在外部是通过定义的 <em>name</em> 来获取的。组合名必须是有效的Python标识符，并且每个组合名只能用一个正则表达式定义，只能定义一次。一个符号组合同样是一个数字组合，就像这个组合没有被命名一样。</p>
<p>命名组合可以在三种上下文中引用。如果样式是 <code class="docutils literal notranslate"><span class="pre">(?P&lt;quote&gt;['&quot;]).*?(?P=quote)</span></code> （也就是说，匹配单引号或者双引号括起来的字符串)：</p>
<table border="1" class="last docutils">
<colgroup>
<col width="53%" />
<col width="47%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">引用组合 &quot;quote&quot; 的上下文</th>
<th class="head">引用方法</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>在正则式自身内</td>
<td><ul class="first last simple">
<li><code class="docutils literal notranslate"><span class="pre">(?P=quote)</span></code> (如示)</li>
<li><code class="docutils literal notranslate"><span class="pre">\1</span></code></li>
</ul>
</td>
</tr>
<tr class="row-odd"><td>处理匹配对象 <em>m</em></td>
<td><ul class="first last simple">
<li><code class="docutils literal notranslate"><span class="pre">m.group('quote')</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">m.end('quote')</span></code> (等)</li>
</ul>
</td>
</tr>
<tr class="row-even"><td>传递到 <code class="docutils literal notranslate"><span class="pre">re.sub()</span></code> 里的 <em>repl</em> 参数中</td>
<td><ul class="first last simple">
<li><code class="docutils literal notranslate"><span class="pre">\g&lt;quote&gt;</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">\g&lt;1&gt;</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">\1</span></code></li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd>
</dl>
<dl class="docutils" id="index-18">
<dt><code class="docutils literal notranslate"><span class="pre">(?P=name)</span></code></dt>
<dd>反向引用一个命名组合；它匹配前面那个叫 <em>name</em> 的命名组中匹配到的串同样的字串。</dd>
</dl>
<dl class="docutils" id="index-19">
<dt><code class="docutils literal notranslate"><span class="pre">(?#…)</span></code></dt>
<dd>注释；里面的内容会被忽略。</dd>
</dl>
<dl class="docutils" id="index-20">
<dt><code class="docutils literal notranslate"><span class="pre">(?=…)</span></code></dt>
<dd>匹配 <code class="docutils literal notranslate"><span class="pre">…</span></code> 的内容，但是并不消费样式的内容。这个叫做 <em class="dfn">lookahead assertion</em>。比如， <code class="docutils literal notranslate"><span class="pre">Isaac</span> <span class="pre">(?=Asimov)</span></code> 匹配 <code class="docutils literal notranslate"><span class="pre">'Isaac</span> <span class="pre">'</span></code> 只有在后面是  <code class="docutils literal notranslate"><span class="pre">'Asimov'</span></code> 的时候。</dd>
</dl>
<dl class="docutils" id="index-21">
<dt><code class="docutils literal notranslate"><span class="pre">(?!…)</span></code></dt>
<dd>匹配 <code class="docutils literal notranslate"><span class="pre">…</span></code> 不符合的情况。这个叫 <em class="dfn">negative lookahead assertion</em> （前视取反）。比如说， <code class="docutils literal notranslate"><span class="pre">Isaac</span> <span class="pre">(?!Asimov)</span></code> 只有后面 <em>不</em> 是 <code class="docutils literal notranslate"><span class="pre">'Asimov'</span></code> 的时候才匹配 <code class="docutils literal notranslate"><span class="pre">'Isaac</span> <span class="pre">'</span></code> 。</dd>
</dl>
<dl class="docutils" id="index-22">
<dt><code class="docutils literal notranslate"><span class="pre">(?&lt;=…)</span></code></dt>
<dd><p class="first">匹配字符串的当前位置，它的前面匹配 <code class="docutils literal notranslate"><span class="pre">…</span></code> 的内容到当前位置。这叫:dfn:<cite>positive lookbehind assertion</cite> （正向后视断定）。 <code class="docutils literal notranslate"><span class="pre">(?&lt;=abc)def</span></code> 会在 <code class="docutils literal notranslate"><span class="pre">'abcdef'</span></code> 中找到一个匹配，因为后视会往后看3个字符并检查是否包含匹配的样式。包含的匹配样式必须是定长的，意思就是 <code class="docutils literal notranslate"><span class="pre">abc</span></code> 或 <code class="docutils literal notranslate"><span class="pre">a|b</span></code> 是允许的，但是 <code class="docutils literal notranslate"><span class="pre">a*</span></code> 和 <code class="docutils literal notranslate"><span class="pre">a{3,4}</span></code> 不可以。注意以 positive lookbehind assertions 开始的样式，如 <code class="docutils literal notranslate"><span class="pre">(?&lt;=abc)def</span></code> ，并不是从 a 开始搜索，而是从 d 往回看的。你可能更加愿意使用 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> 函数，而不是 <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a> 函数：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;(?&lt;=abc)def&#39;</span><span class="p">,</span> <span class="s1">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;def&#39;</span>
</pre></div>
</div>
<p>这个例子搜索一个跟随在连字符后的单词：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(?&lt;=-)\w+&#39;</span><span class="p">,</span> <span class="s1">&#39;spam-egg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;egg&#39;</span>
</pre></div>
</div>
<div class="last versionchanged">
<p><span class="versionmodified">在 3.5 版更改: </span>添加定长组合引用的支持。</p>
</div>
</dd>
</dl>
<dl class="docutils" id="index-23">
<dt><code class="docutils literal notranslate"><span class="pre">(?&lt;!…)</span></code></dt>
<dd>匹配当前位置之前不是 <code class="docutils literal notranslate"><span class="pre">…</span></code> 的样式。这个叫:dfn:<cite>negative lookbehind assertion</cite> （后视断定取非）。类似正向后视断定，包含的样式匹配必须是定长的。由 negative lookbehind assertion 开始的样式可以从字符串搜索开始的位置进行匹配。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?(id/name)yes-pattern|no-pattern)</span></code></dt>
<dd>如果给定的  <em>id</em> 或 <em>name</em> 存在，将会尝试匹配 <code class="docutils literal notranslate"><span class="pre">yes-pattern</span></code> ，否则就尝试匹配 <code class="docutils literal notranslate"><span class="pre">no-pattern</span></code>，<code class="docutils literal notranslate"><span class="pre">no-pattern</span></code> 可选，也可以被忽略。比如， <code class="docutils literal notranslate"><span class="pre">(&lt;)?(\w+&#64;\w+(?:\.\w+)+)(?(1)&gt;|$)</span></code> 是一个email样式匹配，将匹配 <code class="docutils literal notranslate"><span class="pre">'&lt;user&#64;host.com&gt;'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'user&#64;host.com'</span></code> ，但不会匹配 <code class="docutils literal notranslate"><span class="pre">'&lt;user&#64;host.com'</span></code> ，也不会匹配 <code class="docutils literal notranslate"><span class="pre">'user&#64;host.com&gt;'</span></code>。</dd>
</dl>
<p>由 <code class="docutils literal notranslate"><span class="pre">'\'</span></code> 和一个字符组成的特殊序列在以下列出。 如果普通字符不是ASCII数位或者ASCII字母，那么正则样式将匹配第二个字符。比如，<code class="docutils literal notranslate"><span class="pre">\$</span></code> 匹配字符 <code class="docutils literal notranslate"><span class="pre">'$'</span></code>.</p>
<dl class="docutils" id="index-24">
<dt><code class="docutils literal notranslate"><span class="pre">\number</span></code></dt>
<dd>匹配数字代表的组合。每个括号是一个组合，组合从1开始编号。比如 <code class="docutils literal notranslate"><span class="pre">(.+)</span> <span class="pre">\1</span></code> 匹配 <code class="docutils literal notranslate"><span class="pre">'the</span> <span class="pre">the'</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">'55</span> <span class="pre">55'</span></code>, 但不会匹配 <code class="docutils literal notranslate"><span class="pre">'thethe'</span></code> (注意组合后面的空格)。这个特殊序列只能用于匹配前面99个组合。如果  <em>number</em> 的第一个数位是0， 或者 <em>number</em> 是三个八进制数，它将不会被看作是一个组合，而是八进制的数字值。在 <code class="docutils literal notranslate"><span class="pre">'['</span></code> 和 <code class="docutils literal notranslate"><span class="pre">']'</span></code> 字符集合内，任何数字转义都被看作是字符。</dd>
</dl>
<dl class="docutils" id="index-25">
<dt><code class="docutils literal notranslate"><span class="pre">\A</span></code></dt>
<dd>只匹配字符串开始。</dd>
</dl>
<dl class="docutils" id="index-26">
<dt><code class="docutils literal notranslate"><span class="pre">\b</span></code></dt>
<dd><p class="first">匹配空字符串，但只在单词开始或结尾的位置。一个单词被定义为一个单词字符的序列。注意，通常 <code class="docutils literal notranslate"><span class="pre">\b</span></code> 定义为 <code class="docutils literal notranslate"><span class="pre">\w</span></code> 和 <code class="docutils literal notranslate"><span class="pre">\W</span></code> 字符之间，或者 <code class="docutils literal notranslate"><span class="pre">\w</span></code> 和字符串开始/结尾的边界， 意思就是 <code class="docutils literal notranslate"><span class="pre">r'\bfoo\b'</span></code> 匹配 <code class="docutils literal notranslate"><span class="pre">'foo'</span></code>, <code class="docutils literal notranslate"><span class="pre">'foo.'</span></code>, <code class="docutils literal notranslate"><span class="pre">'(foo)'</span></code>, <code class="docutils literal notranslate"><span class="pre">'bar</span> <span class="pre">foo</span> <span class="pre">baz'</span></code> 但不匹配 <code class="docutils literal notranslate"><span class="pre">'foobar'</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">'foo3'</span></code>。</p>
<p class="last">默认情况下，Unicode字母和数字是在Unicode样式中使用的，但是可以用  <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标记来更改。如果 <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> 标记被设置的话，词的边界是由当前语言区域设置决定的，<code class="docutils literal notranslate"><span class="pre">\b</span></code> 表示退格字符，以便与Python字符串文本兼容。</p>
</dd>
</dl>
<dl class="docutils" id="index-27">
<dt><code class="docutils literal notranslate"><span class="pre">\B</span></code></dt>
<dd>匹配空字符串，但 <em>不</em> 能在词的开头或者结尾。意思就是 <code class="docutils literal notranslate"><span class="pre">r'py\B'</span></code> 匹配 <code class="docutils literal notranslate"><span class="pre">'python'</span></code>, <code class="docutils literal notranslate"><span class="pre">'py3'</span></code>, <code class="docutils literal notranslate"><span class="pre">'py2'</span></code>, 但不匹配 <code class="docutils literal notranslate"><span class="pre">'py'</span></code>, <code class="docutils literal notranslate"><span class="pre">'py.'</span></code>, 或者 <code class="docutils literal notranslate"><span class="pre">'py!'</span></code>. <code class="docutils literal notranslate"><span class="pre">\B</span></code> 是 <code class="docutils literal notranslate"><span class="pre">\b</span></code> 的取非，所以Unicode样式的词语是由Unicode字母，数字或下划线构成的，虽然可以用 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标志来改变。如果使用了 <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> 标志，则词的边界由当前语言区域设置。</dd>
</dl>
<dl class="docutils" id="index-28">
<dt><code class="docutils literal notranslate"><span class="pre">\d</span></code></dt>
<dd><dl class="first last docutils">
<dt>对于 Unicode (str) 样式：</dt>
<dd>匹配任何Unicode十进制数（就是在Unicode字符目录[Nd]里的字符）。这包括了 <code class="docutils literal notranslate"><span class="pre">[0-9]</span></code> ，和很多其他的数字字符。如果设置了 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标志，就只匹配 <code class="docutils literal notranslate"><span class="pre">[0-9]</span></code> 。</dd>
<dt>对于8位(bytes)样式：</dt>
<dd>匹配任何十进制数，就是 <code class="docutils literal notranslate"><span class="pre">[0-9]</span></code>。</dd>
</dl>
</dd>
</dl>
<dl class="docutils" id="index-29">
<dt><code class="docutils literal notranslate"><span class="pre">\D</span></code></dt>
<dd>匹配任何非十进制数字的字符。就是 <code class="docutils literal notranslate"><span class="pre">\d</span></code> 取非。 如果设置了 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标志，就相当于 <code class="docutils literal notranslate"><span class="pre">[^0-9]</span></code> 。</dd>
</dl>
<dl class="docutils" id="index-30">
<dt><code class="docutils literal notranslate"><span class="pre">\s</span></code></dt>
<dd><dl class="first last docutils">
<dt>对于 Unicode (str) 样式：</dt>
<dd>匹配任何Unicode空白字符（包括 <code class="docutils literal notranslate"><span class="pre">[</span> <span class="pre">\t\n\r\f\v]</span></code> ，还有很多其他字符，比如不同语言排版规则约定的不换行空格）。如果 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 被设置，就只匹配 <code class="docutils literal notranslate"><span class="pre">[</span> <span class="pre">\t\n\r\f\v]</span></code> 。</dd>
<dt>对于8位(bytes)样式：</dt>
<dd>匹配ASCII中的空白字符，就是 <code class="docutils literal notranslate"><span class="pre">[</span> <span class="pre">\t\n\r\f\v]</span></code> 。</dd>
</dl>
</dd>
</dl>
<dl class="docutils" id="index-31">
<dt><code class="docutils literal notranslate"><span class="pre">\S</span></code></dt>
<dd>匹配任何非空白字符。就是 <code class="docutils literal notranslate"><span class="pre">\s</span></code> 取非。如果设置了 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标志，就相当于 <code class="docutils literal notranslate"><span class="pre">[^</span> <span class="pre">\t\n\r\f\v]</span></code> 。</dd>
</dl>
<dl class="docutils" id="index-32">
<dt><code class="docutils literal notranslate"><span class="pre">\w</span></code></dt>
<dd><dl class="first last docutils">
<dt>对于 Unicode (str) 样式：</dt>
<dd>匹配Unicode词语的字符，包含了可以构成词语的绝大部分字符，也包括数字和下划线。如果设置了 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标志，就只匹配 <code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code> 。</dd>
<dt>对于8位(bytes)样式：</dt>
<dd>匹配ASCII字符中的数字和字母和下划线，就是 <code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code> 。如果设置了 <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> 标记，就匹配当前语言区域的数字和字母和下划线。</dd>
</dl>
</dd>
</dl>
<dl class="docutils" id="index-33">
<dt><code class="docutils literal notranslate"><span class="pre">\W</span></code></dt>
<dd>匹配任何非词语字符。是 <code class="docutils literal notranslate"><span class="pre">\w</span></code> 取非。如果设置了 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标记，就相当于 <code class="docutils literal notranslate"><span class="pre">[^a-zA-Z0-9_]</span></code> 。如果设置了 <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> 标志，就匹配当前语言区域的 <em>非</em> 词语字符。</dd>
</dl>
<dl class="docutils" id="index-34">
<dt><code class="docutils literal notranslate"><span class="pre">\Z</span></code></dt>
<dd>只匹配字符串尾。</dd>
</dl>
<p id="index-35">绝大部分Python的标准转义字符也被正则表达式分析器支持。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span>\<span class="n">a</span>      \<span class="n">b</span>      \<span class="n">f</span>      \<span class="n">n</span>
\<span class="n">r</span>      \<span class="n">t</span>      \<span class="n">u</span>      \<span class="n">U</span>
\<span class="n">v</span>      \<span class="n">x</span>      \\
</pre></div>
</div>
<p>（注意 <code class="docutils literal notranslate"><span class="pre">\b</span></code> 被用于表示词语的边界，它只在字符集合内表示退格，比如 <code class="docutils literal notranslate"><span class="pre">[\b]</span></code> 。）</p>
<p><code class="docutils literal notranslate"><span class="pre">'\u'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'\U'</span></code> 转义序列只在 Unicode 样式中支持。 在 bytes 算啊看会显示错误。 未知的 ASCII 字符转义序列保留在未来使用，会被当作错误来处理。</p>
<p>八进制转义包含为一个有限形式。如果首位数字是 0， 或者有三个八进制数位，那么就认为它是八进制转义。其他的情况，就看作是组引用。对于字符串文本，八进制转义最多有三个数位长。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.3 版更改: </span>增加了 <code class="docutils literal notranslate"><span class="pre">'\u'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'\U'</span></code> 转义序列。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.6 版更改: </span>由 <code class="docutils literal notranslate"><span class="pre">'\'</span></code> 和一个ASCII字符组成的未知转义会被看成错误。</p>
</div>
</div>
<div class="section" id="module-contents">
<span id="contents-of-module-re"></span><h2>模块内容<a class="headerlink" href="#module-contents" title="永久链接至标题">¶</a></h2>
<p>模块定义了几个函数，常量，和一个例外。有些函数是编译后的正则表达式方法的简化版本（少了一些特性）。绝大部分重要的应用，总是会先将正则表达式编译，之后在进行操作。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.6 版更改: </span>标志常量现在是 <code class="xref py py-class docutils literal notranslate"><span class="pre">RegexFlag</span></code> 类的实例，这个类是 <a class="reference internal" href="enum.html#enum.IntFlag" title="enum.IntFlag"><code class="xref py py-class docutils literal notranslate"><span class="pre">enum.IntFlag</span></code></a> 的子类。</p>
</div>
<dl class="function">
<dt id="re.compile">
<code class="descclassname">re.</code><code class="descname">compile</code><span class="sig-paren">(</span><em>pattern</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.compile" title="永久链接至目标">¶</a></dt>
<dd><p>将正则表达式的样式编译为一个 <a class="reference internal" href="#re-objects"><span class="std std-ref">正则表达式对象</span></a>  （正则对象），可以用于匹配，通过这个对象的方法  <a class="reference internal" href="#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a>, <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> 以及其他如下描述。</p>
<p>这个表达式的行为可以通过指定 <em>标记</em> 的值来改变。值可以是以下任意变量，可以通过位的OR操作来结合（ <code class="docutils literal notranslate"><span class="pre">|</span></code> 操作符）。</p>
<p>序列</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">prog</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">pattern</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">prog</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
</pre></div>
</div>
<p>等价于</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">pattern</span><span class="p">,</span> <span class="n">string</span><span class="p">)</span>
</pre></div>
</div>
<p>如果需要多次使用这个正则表达式的话，使用 <a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> 和保存这个正则对象以便复用，可以让程序更加高效。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">通过 <a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> 编译后的样式，和模块级的函数会被缓存， 所以少数的正则表达式使用无需考虑编译的问题。</p>
</div>
</dd></dl>

<dl class="data">
<dt id="re.A">
<code class="descclassname">re.</code><code class="descname">A</code><a class="headerlink" href="#re.A" title="永久链接至目标">¶</a></dt>
<dt id="re.ASCII">
<code class="descclassname">re.</code><code class="descname">ASCII</code><a class="headerlink" href="#re.ASCII" title="永久链接至目标">¶</a></dt>
<dd><p>让 <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code>, <code class="docutils literal notranslate"><span class="pre">\d</span></code>, <code class="docutils literal notranslate"><span class="pre">\D</span></code>, <code class="docutils literal notranslate"><span class="pre">\s</span></code> 和 <code class="docutils literal notranslate"><span class="pre">\S</span></code> 只匹配ASCII，而不是Unicode。这只对Unicode样式有效，会被byte样式忽略。相当于前面语法中的内联标志 <code class="docutils literal notranslate"><span class="pre">(?a)</span></code> 。</p>
<p>注意，为了保持向后兼容， <code class="xref py py-const docutils literal notranslate"><span class="pre">re.U</span></code> 标记依然存在（还有他的同义  <code class="xref py py-const docutils literal notranslate"><span class="pre">re.UNICODE</span></code> 和嵌入形式 <code class="docutils literal notranslate"><span class="pre">(?u)</span></code> ) ， 但是这些在 Python 3 是冗余的，因为默认字符串已经是Unicode了（并且Unicode匹配不允许byte出现)。</p>
</dd></dl>

<dl class="data">
<dt id="re.DEBUG">
<code class="descclassname">re.</code><code class="descname">DEBUG</code><a class="headerlink" href="#re.DEBUG" title="永久链接至目标">¶</a></dt>
<dd><p>显示编译时的debug信息，没有内联标记。</p>
</dd></dl>

<dl class="data">
<dt id="re.I">
<code class="descclassname">re.</code><code class="descname">I</code><a class="headerlink" href="#re.I" title="永久链接至目标">¶</a></dt>
<dt id="re.IGNORECASE">
<code class="descclassname">re.</code><code class="descname">IGNORECASE</code><a class="headerlink" href="#re.IGNORECASE" title="永久链接至目标">¶</a></dt>
<dd><p>进行忽略大小写匹配；表达式如 <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> 也会匹配小写字符。Unicode匹配（比如 <code class="docutils literal notranslate"><span class="pre">Ü</span></code> 匹配 <code class="docutils literal notranslate"><span class="pre">ü</span></code>）同样有用，除非设置了 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.ASCII</span></code></a> 标记来禁用非ASCII匹配。当前语言区域不会改变这个标记，除非设置了 <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.LOCALE</span></code></a> 标记。这个相当于内联标记 <code class="docutils literal notranslate"><span class="pre">(?i)</span></code> 。</p>
<p>注意，当设置了 <a class="reference internal" href="#re.IGNORECASE" title="re.IGNORECASE"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code></a> 标记，搜索Unicode样式 <code class="docutils literal notranslate"><span class="pre">[a-z]</span></code> 或 <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> 的结合时，它将会匹配52个ASCII字符和4个额外的非ASCII字符： 'İ' (U+0130, 拉丁大写的 I 带个点在上面), 'ı' (U+0131, 拉丁小写没有点的 I ), 'ſ' (U+017F, 拉丁小写长 s) and 'K' (U+212A, 开尔文符号).如果使用 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a> 标记，就只匹配 'a' 到 'z' 和 'A' 到 'Z' 。</p>
</dd></dl>

<dl class="data">
<dt id="re.L">
<code class="descclassname">re.</code><code class="descname">L</code><a class="headerlink" href="#re.L" title="永久链接至目标">¶</a></dt>
<dt id="re.LOCALE">
<code class="descclassname">re.</code><code class="descname">LOCALE</code><a class="headerlink" href="#re.LOCALE" title="永久链接至目标">¶</a></dt>
<dd><p>由当前语言区域决定 <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code> 和大小写敏感匹配。这个标记只能对byte样式有效。这个标记不推荐使用，因为语言区域机制很不可靠，它一次只能处理一个 &quot;习惯”，而且只对8位字节有效。Unicode匹配在Python 3 里默认启用，并可以处理不同语言。 这个对应内联标记 <code class="docutils literal notranslate"><span class="pre">(?L)</span></code> 。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.6 版更改: </span><a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.LOCALE</span></code></a> 只能用于byte样式，而且不能和 <a class="reference internal" href="#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.ASCII</span></code></a> 一起用。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>设置了 <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.LOCALE</span></code></a> 标记的编译正则对象不再在编译时依赖语言区域设置。语言区域设置只在匹配的时候影响其结果。</p>
</div>
</dd></dl>

<dl class="data">
<dt id="re.M">
<code class="descclassname">re.</code><code class="descname">M</code><a class="headerlink" href="#re.M" title="永久链接至目标">¶</a></dt>
<dt id="re.MULTILINE">
<code class="descclassname">re.</code><code class="descname">MULTILINE</code><a class="headerlink" href="#re.MULTILINE" title="永久链接至目标">¶</a></dt>
<dd><p>设置以后，样式字符 <code class="docutils literal notranslate"><span class="pre">'^'</span></code> 匹配字符串的开始，和每一行的开始（换行符后面紧跟的符号）；样式字符 <code class="docutils literal notranslate"><span class="pre">'$'</span></code> 匹配字符串尾，和每一行的结尾（换行符前面那个符号）。默认情况下，<code class="docutils literal notranslate"><span class="pre">’^’</span></code> 匹配字符串头，<code class="docutils literal notranslate"><span class="pre">'$'</span></code> 匹配字符串尾。对应内联标记 <code class="docutils literal notranslate"><span class="pre">(?m)</span></code> 。</p>
</dd></dl>

<dl class="data">
<dt id="re.S">
<code class="descclassname">re.</code><code class="descname">S</code><a class="headerlink" href="#re.S" title="永久链接至目标">¶</a></dt>
<dt id="re.DOTALL">
<code class="descclassname">re.</code><code class="descname">DOTALL</code><a class="headerlink" href="#re.DOTALL" title="永久链接至目标">¶</a></dt>
<dd><p>让 <code class="docutils literal notranslate"><span class="pre">'.'</span></code> 特殊字符匹配任何字符，包括换行符；如果没有这个标记，<code class="docutils literal notranslate"><span class="pre">'.'</span></code> 就匹配 <em>除了</em> 换行符的其他任意字符。对应内联标记 <code class="docutils literal notranslate"><span class="pre">(?s)</span></code> 。</p>
</dd></dl>

<dl class="data">
<dt id="re.X">
<code class="descclassname">re.</code><code class="descname">X</code><a class="headerlink" href="#re.X" title="永久链接至目标">¶</a></dt>
<dt id="re.VERBOSE">
<code class="descclassname">re.</code><code class="descname">VERBOSE</code><a class="headerlink" href="#re.VERBOSE" title="永久链接至目标">¶</a></dt>
<dd><p id="index-36">这个标记允许你编写更具可读性更友好的正则表达式。通过分段和添加注释。空白符号会被忽略，除非在一个字符集合当中或者由反斜杠转义，或者在 <code class="docutils literal notranslate"><span class="pre">*?</span></code>, <code class="docutils literal notranslate"><span class="pre">(?:</span></code> or <code class="docutils literal notranslate"><span class="pre">(?P&lt;…&gt;</span></code> 分组之内。当一个行内有 <code class="docutils literal notranslate"><span class="pre">#</span></code> 不在字符集和转义序列，那么它之后的所有字符都是注释。</p>
<p>意思就是下面两个正则表达式等价地匹配一个十进制数字：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;&quot;&quot;\d +  # the integral part</span>
<span class="s2">                   \.    # the decimal point</span>
<span class="s2">                   \d *  # some fractional digits&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">X</span><span class="p">)</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\d+\.\d*&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>对应内联标记 <code class="docutils literal notranslate"><span class="pre">(?x)</span></code> 。</p>
</dd></dl>

<dl class="function">
<dt id="re.search">
<code class="descclassname">re.</code><code class="descname">search</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.search" title="永久链接至目标">¶</a></dt>
<dd><p>扫描整个 <em>字符串</em> 找到匹配样式的第一个位置，并返回一个相应的 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a>。如果没有匹配，就返回一个 <code class="docutils literal notranslate"><span class="pre">None</span></code> ； 注意这和找到一个零长度匹配是不同的。</p>
</dd></dl>

<dl class="function">
<dt id="re.match">
<code class="descclassname">re.</code><code class="descname">match</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.match" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <em>string</em> 开始的0或者多个字符匹配到了正则表达式样式，就返回一个相应的 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a> 。 如果没有匹配，就返回 <code class="docutils literal notranslate"><span class="pre">None</span></code> ；注意它跟零长度匹配是不同的。</p>
<p>注意即便是 <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> 多行模式， <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a> 也只匹配字符串的开始位置，而不匹配每行开始。</p>
<p>如果你想定位 <em>string</em> 的任何位置，使用 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> 来替代（也可参考 <a class="reference internal" href="#search-vs-match"><span class="std std-ref">search() vs. match()</span></a> ）</p>
</dd></dl>

<dl class="function">
<dt id="re.fullmatch">
<code class="descclassname">re.</code><code class="descname">fullmatch</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.fullmatch" title="永久链接至目标">¶</a></dt>
<dd><p>如果整个 <em>string</em> 匹配到正则表达式样式，就返回一个相应的 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a> 。 否则就返回一个 <code class="docutils literal notranslate"><span class="pre">None</span></code> ；注意这跟零长度匹配是不同的。</p>
<div class="versionadded">
<p><span class="versionmodified">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.split">
<code class="descclassname">re.</code><code class="descname">split</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>maxsplit=0</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.split" title="永久链接至目标">¶</a></dt>
<dd><p>用 <em>pattern</em> 分开  <em>string</em> 。 如果在 <em>pattern</em> 中捕获到括号，那么所有的组里的文字也会包含在列表里。如果 <em>maxsplit</em> 非零， 最多进行 <em>maxsplit</em> 次分隔， 剩下的字符全部返回到列表的最后一个元素。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\W+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words&#39;, &#39;words&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(\W+)&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;.&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\W+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words, words.&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;[a-f]+&#39;</span><span class="p">,</span> <span class="s1">&#39;0a3B9&#39;</span><span class="p">,</span> <span class="n">flags</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
<span class="go">[&#39;0&#39;, &#39;3&#39;, &#39;9&#39;]</span>
</pre></div>
</div>
<p>如果分隔符里有捕获组合，并且匹配到字符串的开始，那么结果将会以一个空字符串开始。对于结尾也是一样</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(\W+)&#39;</span><span class="p">,</span> <span class="s1">&#39;...words, words...&#39;</span><span class="p">)</span>
<span class="go">[&#39;&#39;, &#39;...&#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;...&#39;, &#39;&#39;]</span>
</pre></div>
</div>
<p>这样的话，分隔组将会出现在结果列表中同样的位置。</p>
<p>样式的空匹配将分开字符串，但只在不相临的状况生效。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\b&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;&#39;, &#39;Words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;.&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\W*&#39;</span><span class="p">,</span> <span class="s1">&#39;...words...&#39;</span><span class="p">)</span>
<span class="go">[&#39;&#39;, &#39;&#39;, &#39;w&#39;, &#39;o&#39;, &#39;r&#39;, &#39;d&#39;, &#39;s&#39;, &#39;&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(\W*)&#39;</span><span class="p">,</span> <span class="s1">&#39;...words...&#39;</span><span class="p">)</span>
<span class="go">[&#39;&#39;, &#39;...&#39;, &#39;&#39;, &#39;&#39;, &#39;w&#39;, &#39;&#39;, &#39;o&#39;, &#39;&#39;, &#39;r&#39;, &#39;&#39;, &#39;d&#39;, &#39;&#39;, &#39;s&#39;, &#39;...&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;]</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.1 版更改: </span>增加了可选标记参数。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>增加了空字符串的样式分隔。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.findall">
<code class="descclassname">re.</code><code class="descname">findall</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.findall" title="永久链接至目标">¶</a></dt>
<dd><p>对 <em>string</em> 返回一个不重复的 <em>pattern</em> 的匹配列表， <em>string</em> 从左到右进行扫描，匹配按找到的顺序返回。如果样式里存在一到多个组，就返回一个组合列表；就是一个元组的列表（如果样式里有超过一个组合的话）。空匹配也会包含在结果里。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>非空匹配现在可以在前一个空匹配之后出现了。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.finditer">
<code class="descclassname">re.</code><code class="descname">finditer</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.finditer" title="永久链接至目标">¶</a></dt>
<dd><p><em>pattern</em> 在 <em>string</em> 里所有的非重复匹配，返回为一个迭代器  <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> 保存了  <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a> 。 <em>string</em> 从左到右扫描，匹配按顺序排列。空匹配也包含在结果里。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>非空匹配现在可以在前一个空匹配之后出现了。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.sub">
<code class="descclassname">re.</code><code class="descname">sub</code><span class="sig-paren">(</span><em>pattern</em>, <em>repl</em>, <em>string</em>, <em>count=0</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.sub" title="永久链接至目标">¶</a></dt>
<dd><p>返回通过使用 <em>repl</em> 替换在 <em>string</em> 最左边非重叠出现的 <em>pattern</em> 而获得的字符串。 如果样式没有找到，则不加改变地返回 <em>string</em>。 <em>repl</em> 可以是字符串或函数；如为字符串，则其中任何反斜杠转义序列都会被处理。 也就是说，<code class="docutils literal notranslate"><span class="pre">\n</span></code> 会被转换为一个换行符，<code class="docutils literal notranslate"><span class="pre">\r</span></code> 会被转换为一个回车附，依此类推。 未知的 ASCII 字符转义序列保留在未来使用，会被当作错误来处理。 其他未知转义序列例如 <code class="docutils literal notranslate"><span class="pre">\&amp;</span></code> 会保持原样。 向后引用像是 <code class="docutils literal notranslate"><span class="pre">\6</span></code> 会用样式中第 6 组所匹配到的子字符串来替换。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):&#39;</span><span class="p">,</span>
<span class="gp">... </span>       <span class="sa">r</span><span class="s1">&#39;static PyObject*\npy_\1(void)\n{&#39;</span><span class="p">,</span>
<span class="gp">... </span>       <span class="s1">&#39;def myfunc():&#39;</span><span class="p">)</span>
<span class="go">&#39;static PyObject*\npy_myfunc(void)\n{&#39;</span>
</pre></div>
</div>
<p>如果 <em>repl</em> 是一个函数，那它会对每个非重复的 <em>pattern</em> 的情况调用。这个函数只能有一个 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a> 参数，并返回一个替换后的字符串。比如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">dashrepl</span><span class="p">(</span><span class="n">matchobj</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">matchobj</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="o">==</span> <span class="s1">&#39;-&#39;</span><span class="p">:</span> <span class="k">return</span> <span class="s1">&#39; &#39;</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="s1">&#39;-&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;-{1,2}&#39;</span><span class="p">,</span> <span class="n">dashrepl</span><span class="p">,</span> <span class="s1">&#39;pro----gram-files&#39;</span><span class="p">)</span>
<span class="go">&#39;pro--gram files&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\sAND\s&#39;</span><span class="p">,</span> <span class="s1">&#39; &amp; &#39;</span><span class="p">,</span> <span class="s1">&#39;Baked Beans And Spam&#39;</span><span class="p">,</span> <span class="n">flags</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
<span class="go">&#39;Baked Beans &amp; Spam&#39;</span>
</pre></div>
</div>
<p>样式可以是一个字符串或者一个 <a class="reference internal" href="#re-objects"><span class="std std-ref">样式对象</span></a> 。</p>
<p>可选参数 <em>count</em> 是要替换的最大次数；<em>count</em> 必须是非负整数。如果忽略这个参数，或者设置为0，所有的匹配都会被替换。空匹配只在不相临连续的情况被更替，所以  <code class="docutils literal notranslate"><span class="pre">sub('x*',</span> <span class="pre">'-',</span> <span class="pre">'abxd')</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">'-a-b--d-'</span></code> 。</p>
<p id="index-37">在字符串类型的 <em>repl</em> 参数里，如上所述的转义和向后引用中，<code class="docutils literal notranslate"><span class="pre">\g&lt;name&gt;</span></code> 会使用命名组合 <code class="docutils literal notranslate"><span class="pre">name</span></code>，（在  <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;…)</span></code> 语法中定义） <code class="docutils literal notranslate"><span class="pre">\g&lt;number&gt;</span></code> 会使用数字组；<code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;</span></code> 就是 <code class="docutils literal notranslate"><span class="pre">\2</span></code>，但它避免了二义性，如 <code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;0</span></code>。 <code class="docutils literal notranslate"><span class="pre">\20</span></code> 就会被解释为组20，而不是组2后面跟随一个字符 <code class="docutils literal notranslate"><span class="pre">'0'</span></code>。向后引用 <code class="docutils literal notranslate"><span class="pre">\g&lt;0&gt;</span></code> 把 <em>pattern</em> 作为一整个组进行引用。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.1 版更改: </span>增加了可选标记参数。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5 版更改: </span>不匹配的组合替换为空字符串。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.6 版更改: </span><em>pattern</em> 中的未知转义（由 <code class="docutils literal notranslate"><span class="pre">'\'</span></code> 和一个 ASCII 字符组成）被视为错误。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span><em>repl</em> 中的未知转义（由 <code class="docutils literal notranslate"><span class="pre">'\'</span></code> 和一个 ASCII 字符组成）被视为错误。</p>
<p>样式中的空匹配相邻接时会被替换。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.subn">
<code class="descclassname">re.</code><code class="descname">subn</code><span class="sig-paren">(</span><em>pattern</em>, <em>repl</em>, <em>string</em>, <em>count=0</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.subn" title="永久链接至目标">¶</a></dt>
<dd><p>行为与 <a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> 相同，但是返回一个元组 <code class="docutils literal notranslate"><span class="pre">(字符串,</span> <span class="pre">替换次数)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.1 版更改: </span>增加了可选标记参数。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5 版更改: </span>不匹配的组合替换为空字符串。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.escape">
<code class="descclassname">re.</code><code class="descname">escape</code><span class="sig-paren">(</span><em>pattern</em><span class="sig-paren">)</span><a class="headerlink" href="#re.escape" title="永久链接至目标">¶</a></dt>
<dd><p>转义 <em>pattern</em> 中的特殊字符。如果你想对任意可能包含正则表达式元字符的文本字符串进行匹配，它就是有用的。比如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">(</span><span class="s1">&#39;python.exe&#39;</span><span class="p">))</span>
<span class="go">python\.exe</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">legal_chars</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">ascii_lowercase</span> <span class="o">+</span> <span class="n">string</span><span class="o">.</span><span class="n">digits</span> <span class="o">+</span> <span class="s2">&quot;!#$%&amp;&#39;*+-.^_`|~:&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;[</span><span class="si">%s</span><span class="s1">]+&#39;</span> <span class="o">%</span> <span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">(</span><span class="n">legal_chars</span><span class="p">))</span>
<span class="go">[abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&amp;&#39;\*\+\-\.\^_`\|\~:]+</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">operators</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">,</span> <span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="s1">&#39;/&#39;</span><span class="p">,</span> <span class="s1">&#39;**&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;|&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">,</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">operators</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">))))</span>
<span class="go">/|\-|\+|\*\*|\*</span>
</pre></div>
</div>
<p>这个函数不能用在 <a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> 和 <a class="reference internal" href="#re.subn" title="re.subn"><code class="xref py py-func docutils literal notranslate"><span class="pre">subn()</span></code></a> 的替换字符串里，只有反斜杠应该被转义，比如说</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">digits_re</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;\d+&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sample</span> <span class="o">=</span> <span class="s1">&#39;/usr/sbin/sendmail - 0 errors, 12 warnings&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">digits_re</span><span class="p">,</span> <span class="n">digits_re</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\\</span><span class="s1">&#39;</span><span class="p">,</span> <span class="sa">r</span><span class="s1">&#39;</span><span class="se">\\</span><span class="s1">&#39;</span><span class="p">),</span> <span class="n">sample</span><span class="p">))</span>
<span class="go">/usr/sbin/sendmail - \d+ errors, \d+ warnings</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.3 版更改: </span><code class="docutils literal notranslate"><span class="pre">'_'</span></code> 不再被转义。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>只有在正则表达式中可以产生特殊含义的字符会被转义。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.purge">
<code class="descclassname">re.</code><code class="descname">purge</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#re.purge" title="永久链接至目标">¶</a></dt>
<dd><p>清除正则表达式缓存。</p>
</dd></dl>

<dl class="exception">
<dt id="re.error">
<em class="property">exception </em><code class="descclassname">re.</code><code class="descname">error</code><span class="sig-paren">(</span><em>msg</em>, <em>pattern=None</em>, <em>pos=None</em><span class="sig-paren">)</span><a class="headerlink" href="#re.error" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">raise</span></code> 一个例外。当传递到函数的字符串不是一个有效正则表达式的时候（比如，包含一个不匹配的括号）或者其他错误在编译时或匹配时产生。如果字符串不包含样式匹配，是不会被视为错误的。错误实例有以下附加属性：</p>
<dl class="attribute">
<dt id="re.error.msg">
<code class="descname">msg</code><a class="headerlink" href="#re.error.msg" title="永久链接至目标">¶</a></dt>
<dd><p>未格式化的错误消息。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.error.pattern">
<code class="descname">pattern</code><a class="headerlink" href="#re.error.pattern" title="永久链接至目标">¶</a></dt>
<dd><p>正则表达式样式。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.error.pos">
<code class="descname">pos</code><a class="headerlink" href="#re.error.pos" title="永久链接至目标">¶</a></dt>
<dd><p>编译失败的 <em>pattern</em> 的位置索引（可以是 <code class="docutils literal notranslate"><span class="pre">None</span></code> ）。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.error.lineno">
<code class="descname">lineno</code><a class="headerlink" href="#re.error.lineno" title="永久链接至目标">¶</a></dt>
<dd><p>对应 <em>pos</em> (可以是 <code class="docutils literal notranslate"><span class="pre">None</span></code>) 的行号。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.error.colno">
<code class="descname">colno</code><a class="headerlink" href="#re.error.colno" title="永久链接至目标">¶</a></dt>
<dd><p>对应 <em>pos</em> (可以是 <code class="docutils literal notranslate"><span class="pre">None</span></code>) 的列号。</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">在 3.5 版更改: </span>添加了附加属性。</p>
</div>
</dd></dl>

</div>
<div class="section" id="regular-expression-objects">
<span id="re-objects"></span><h2>正则表达式对象 （正则对象）<a class="headerlink" href="#regular-expression-objects" title="永久链接至标题">¶</a></h2>
<p>编译后的正则表达式对象支持一下方法和属性：</p>
<dl class="method">
<dt id="re.Pattern.search">
<code class="descclassname">Pattern.</code><code class="descname">search</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.search" title="永久链接至目标">¶</a></dt>
<dd><p>扫描整个 <em>string</em> 寻找第一个匹配的位置， 并返回一个相应的 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a>。如果没有匹配，就返回 <code class="docutils literal notranslate"><span class="pre">None</span></code> ；注意它和零长度匹配是不同的。</p>
<p>可选的第二个参数 <em>pos</em> 给出了字符串中开始搜索的位置索引；默认为 <code class="docutils literal notranslate"><span class="pre">0</span></code>，它不完全等价于字符串切片； <code class="docutils literal notranslate"><span class="pre">'^'</span></code> 样式字符匹配字符串真正的开头，和换行符后面的第一个字符，但不会匹配索引规定开始的位置。</p>
<p>可选参数 <em>endpos</em> 限定了字符串搜索的结束；它假定字符串长度到 <em>endpos</em> ， 所以只有从 <code class="docutils literal notranslate"><span class="pre">pos</span></code> 到 <code class="docutils literal notranslate"><span class="pre">endpos</span> <span class="pre">-</span> <span class="pre">1</span></code> 的字符会被匹配。如果 <em>endpos</em> 小于 <em>pos</em>，就不会有匹配产生；另外，如果 <em>rx</em> 是一个编译后的正则对象， <code class="docutils literal notranslate"><span class="pre">rx.search(string,</span> <span class="pre">0,</span> <span class="pre">50)</span></code> 等价于 <code class="docutils literal notranslate"><span class="pre">rx.search(string[:50],</span> <span class="pre">0)</span></code>。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;d&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">)</span>     <span class="c1"># Match at index 0</span>
<span class="go">&lt;re.Match object; span=(0, 1), match=&#39;d&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>  <span class="c1"># No match; search doesn&#39;t include the &quot;d&quot;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Pattern.match">
<code class="descclassname">Pattern.</code><code class="descname">match</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.match" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <em>string</em> 的 <em>开始位置</em> 能够找到这个正则样式的任意个匹配，就返回一个相应的 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a>。如果不匹配，就返回 <code class="docutils literal notranslate"><span class="pre">None</span></code> ；注意它与零长度匹配是不同的。</p>
<p>可选参数 <em>pos</em> 和 <em>endpos</em> 与 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 含义相同。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;o&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">)</span>      <span class="c1"># No match as &quot;o&quot; is not at the start of &quot;dog&quot;.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>   <span class="c1"># Match as &quot;o&quot; is the 2nd character of &quot;dog&quot;.</span>
<span class="go">&lt;re.Match object; span=(1, 2), match=&#39;o&#39;&gt;</span>
</pre></div>
</div>
<p>如果你想定位匹配在 <em>string</em> 中的位置，使用 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 来替代（另参考  <a class="reference internal" href="#search-vs-match"><span class="std std-ref">search() vs. match()</span></a>）。</p>
</dd></dl>

<dl class="method">
<dt id="re.Pattern.fullmatch">
<code class="descclassname">Pattern.</code><code class="descname">fullmatch</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.fullmatch" title="永久链接至目标">¶</a></dt>
<dd><p>如果整个 <em>string</em> 匹配这个正则表达式，就返回一个相应的 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a> 。 否则就返回 <code class="docutils literal notranslate"><span class="pre">None</span></code> ； 注意跟零长度匹配是不同的。</p>
<p>可选参数 <em>pos</em> 和 <em>endpos</em> 与 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 含义相同。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;o[gh]&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">fullmatch</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">)</span>      <span class="c1"># No match as &quot;o&quot; is not at the start of &quot;dog&quot;.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">fullmatch</span><span class="p">(</span><span class="s2">&quot;ogre&quot;</span><span class="p">)</span>     <span class="c1"># No match as not the full string matches.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">fullmatch</span><span class="p">(</span><span class="s2">&quot;doggie&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>   <span class="c1"># Matches within given limits.</span>
<span class="go">&lt;re.Match object; span=(1, 3), match=&#39;og&#39;&gt;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Pattern.split">
<code class="descclassname">Pattern.</code><code class="descname">split</code><span class="sig-paren">(</span><em>string</em>, <em>maxsplit=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.split" title="永久链接至目标">¶</a></dt>
<dd><p>等价于 <a class="reference internal" href="#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a> 函数，使用了编译后的样式。</p>
</dd></dl>

<dl class="method">
<dt id="re.Pattern.findall">
<code class="descclassname">Pattern.</code><code class="descname">findall</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.findall" title="永久链接至目标">¶</a></dt>
<dd><p>类似函数 <a class="reference internal" href="#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a> ， 使用了编译后样式，但也可以接收可选参数 <em>pos</em> 和 <em>endpos</em> ，限制搜索范围，就像 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="re.Pattern.finditer">
<code class="descclassname">Pattern.</code><code class="descname">finditer</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.finditer" title="永久链接至目标">¶</a></dt>
<dd><p>类似函数 <code class="xref py py-func docutils literal notranslate"><span class="pre">finiter()</span></code> ， 使用了编译后样式，但也可以接收可选参数 <em>pos</em> 和 <em>endpos</em> ，限制搜索范围，就像 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="re.Pattern.sub">
<code class="descclassname">Pattern.</code><code class="descname">sub</code><span class="sig-paren">(</span><em>repl</em>, <em>string</em>, <em>count=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.sub" title="永久链接至目标">¶</a></dt>
<dd><p>等价于 <a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> 函数，使用了编译后的样式。</p>
</dd></dl>

<dl class="method">
<dt id="re.Pattern.subn">
<code class="descclassname">Pattern.</code><code class="descname">subn</code><span class="sig-paren">(</span><em>repl</em>, <em>string</em>, <em>count=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.Pattern.subn" title="永久链接至目标">¶</a></dt>
<dd><p>等价于 <a class="reference internal" href="#re.subn" title="re.subn"><code class="xref py py-func docutils literal notranslate"><span class="pre">subn()</span></code></a> 函数，使用了编译后的样式。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Pattern.flags">
<code class="descclassname">Pattern.</code><code class="descname">flags</code><a class="headerlink" href="#re.Pattern.flags" title="永久链接至目标">¶</a></dt>
<dd><p>正则匹配标记。这是可以传递给 <a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> 的参数，任何 <code class="docutils literal notranslate"><span class="pre">(?…)</span></code> 内联标记，隐性标记比如 <code class="xref py py-data docutils literal notranslate"><span class="pre">UNICODE</span></code> 的结合。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Pattern.groups">
<code class="descclassname">Pattern.</code><code class="descname">groups</code><a class="headerlink" href="#re.Pattern.groups" title="永久链接至目标">¶</a></dt>
<dd><p>捕获组合的数量。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Pattern.groupindex">
<code class="descclassname">Pattern.</code><code class="descname">groupindex</code><a class="headerlink" href="#re.Pattern.groupindex" title="永久链接至目标">¶</a></dt>
<dd><p>映射由 <code class="docutils literal notranslate"><span class="pre">(?P&lt;id&gt;)</span></code> 定义的命名符号组合和数字组合的字典。如果没有符号组，那字典就是空的。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Pattern.pattern">
<code class="descclassname">Pattern.</code><code class="descname">pattern</code><a class="headerlink" href="#re.Pattern.pattern" title="永久链接至目标">¶</a></dt>
<dd><p>编译对象的原始样式字符串。</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>添加 <a class="reference internal" href="copy.html#copy.copy" title="copy.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.copy()</span></code></a> 和 <a class="reference internal" href="copy.html#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.deepcopy()</span></code></a> 函数的支持。编译后的正则表达式对象被认为是原子性的。</p>
</div>
</div>
<div class="section" id="match-objects">
<span id="id2"></span><h2>匹配对象<a class="headerlink" href="#match-objects" title="永久链接至标题">¶</a></h2>
<p>匹配对象总是有一个布尔值 <code class="docutils literal notranslate"><span class="pre">True</span></code>。如果没有匹配的话 <a class="reference internal" href="#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> 和 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 返回 <code class="docutils literal notranslate"><span class="pre">None</span></code> 所以你可以简单的用 <code class="docutils literal notranslate"><span class="pre">if</span></code> 语句来判断是否匹配</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">match</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">pattern</span><span class="p">,</span> <span class="n">string</span><span class="p">)</span>
<span class="k">if</span> <span class="n">match</span><span class="p">:</span>
    <span class="n">process</span><span class="p">(</span><span class="n">match</span><span class="p">)</span>
</pre></div>
</div>
<p>匹配对象支持以下方法和属性：</p>
<dl class="method">
<dt id="re.Match.expand">
<code class="descclassname">Match.</code><code class="descname">expand</code><span class="sig-paren">(</span><em>template</em><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.expand" title="永久链接至目标">¶</a></dt>
<dd><p>对 <em>template</em> 进行反斜杠转义替换并且返回，就像 <a class="reference internal" href="#re.Pattern.sub" title="re.Pattern.sub"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code></a> 方法中一样。转义如同 <code class="docutils literal notranslate"><span class="pre">\n</span></code> 被转换成合适的字符，数字引用(<code class="docutils literal notranslate"><span class="pre">\1</span></code>, <code class="docutils literal notranslate"><span class="pre">\2</span></code>)和命名组合(<code class="docutils literal notranslate"><span class="pre">\g&lt;1&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">\g&lt;name&gt;</span></code>) 替换为相应组合的内容。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5 版更改: </span>不匹配的组合替换为空字符串。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Match.group">
<code class="descclassname">Match.</code><code class="descname">group</code><span class="sig-paren">(</span><span class="optional">[</span><em>group1</em>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.group" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个或者多个匹配的子组。如果只有一个参数，结果就是一个字符串，如果有多个参数，结果就是一个元组（每个参数对应一个项），如果没有参数，组1默认到0（整个匹配都被返回）。 如果一个组N 参数值为 0，相应的返回值就是整个匹配字符串；如果它是一个范围 [1..99]，结果就是相应的括号组字符串。如果一个组号是负数，或者大于样式中定义的组数，一个 <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> 索引错误就 <code class="docutils literal notranslate"><span class="pre">raise</span></code>。如果一个组包含在样式的一部分，并被匹配多次，就返回最后一个匹配。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\w+) (\w+)&quot;</span><span class="p">,</span> <span class="s2">&quot;Isaac Newton, physicist&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>       <span class="c1"># The entire match</span>
<span class="go">&#39;Isaac Newton&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>       <span class="c1"># The first parenthesized subgroup.</span>
<span class="go">&#39;Isaac&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>       <span class="c1"># The second parenthesized subgroup.</span>
<span class="go">&#39;Newton&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>    <span class="c1"># Multiple arguments give us a tuple.</span>
<span class="go">(&#39;Isaac&#39;, &#39;Newton&#39;)</span>
</pre></div>
</div>
<p>如果正则表达式使用了 <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;…)</span></code> 语法， <em>groupN</em> 参数就也可能是命名组合的名字。如果一个字符串参数在样式中未定义为组合名，一个 <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> 就 <code class="docutils literal notranslate"><span class="pre">raise</span></code>。</p>
<p>一个相对复杂的例子</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(?P&lt;first_name&gt;\w+) (?P&lt;last_name&gt;\w+)&quot;</span><span class="p">,</span> <span class="s2">&quot;Malcolm Reynolds&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s1">&#39;first_name&#39;</span><span class="p">)</span>
<span class="go">&#39;Malcolm&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s1">&#39;last_name&#39;</span><span class="p">)</span>
<span class="go">&#39;Reynolds&#39;</span>
</pre></div>
</div>
<p>命名组合同样可以通过索引值引用</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;Malcolm&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&#39;Reynolds&#39;</span>
</pre></div>
</div>
<p>如果一个组匹配成功多次，就只返回最后一个匹配</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(..)+&quot;</span><span class="p">,</span> <span class="s2">&quot;a1b2c3&quot;</span><span class="p">)</span>  <span class="c1"># Matches 3 times.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>                        <span class="c1"># Returns only the last match.</span>
<span class="go">&#39;c3&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Match.__getitem__">
<code class="descclassname">Match.</code><code class="descname">__getitem__</code><span class="sig-paren">(</span><em>g</em><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.__getitem__" title="永久链接至目标">¶</a></dt>
<dd><p>这个等价于 <code class="docutils literal notranslate"><span class="pre">m.group(g)</span></code>。这允许更方便的引用一个匹配</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\w+) (\w+)&quot;</span><span class="p">,</span> <span class="s2">&quot;Isaac Newton, physicist&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>       <span class="c1"># The entire match</span>
<span class="go">&#39;Isaac Newton&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>       <span class="c1"># The first parenthesized subgroup.</span>
<span class="go">&#39;Isaac&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>       <span class="c1"># The second parenthesized subgroup.</span>
<span class="go">&#39;Newton&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">3.6 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Match.groups">
<code class="descclassname">Match.</code><code class="descname">groups</code><span class="sig-paren">(</span><em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.groups" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个元组，包含所有匹配的子组，在样式中出现的从1到任意多的组合。 <em>default</em> 参数用于不参与匹配的情况，默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\d+)\.(\d+)&quot;</span><span class="p">,</span> <span class="s2">&quot;24.1632&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">(&#39;24&#39;, &#39;1632&#39;)</span>
</pre></div>
</div>
<p>如果我们使小数点可选，那么不是所有的组都会参与到匹配当中。这些组合默认会返回一个 <code class="docutils literal notranslate"><span class="pre">None</span></code> ，除非指定了 <em>default</em> 参数。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\d+)\.?(\d+)?&quot;</span><span class="p">,</span> <span class="s2">&quot;24&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>      <span class="c1"># Second group defaults to None.</span>
<span class="go">(&#39;24&#39;, None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">(</span><span class="s1">&#39;0&#39;</span><span class="p">)</span>   <span class="c1"># Now, the second group defaults to &#39;0&#39;.</span>
<span class="go">(&#39;24&#39;, &#39;0&#39;)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Match.groupdict">
<code class="descclassname">Match.</code><code class="descname">groupdict</code><span class="sig-paren">(</span><em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.groupdict" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个字典，包含了所有的 <em>命名</em> 子组。key就是组名。 <em>default</em> 参数用于不参与匹配的组合；默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。 例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(?P&lt;first_name&gt;\w+) (?P&lt;last_name&gt;\w+)&quot;</span><span class="p">,</span> <span class="s2">&quot;Malcolm Reynolds&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groupdict</span><span class="p">()</span>
<span class="go">{&#39;first_name&#39;: &#39;Malcolm&#39;, &#39;last_name&#39;: &#39;Reynolds&#39;}</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Match.start">
<code class="descclassname">Match.</code><code class="descname">start</code><span class="sig-paren">(</span><span class="optional">[</span><em>group</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.start" title="永久链接至目标">¶</a></dt>
<dt id="re.Match.end">
<code class="descclassname">Match.</code><code class="descname">end</code><span class="sig-paren">(</span><span class="optional">[</span><em>group</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.end" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <em>group</em> 匹配到的字串的开始和结束标号。<em>group</em> 默认为0（意思是整个匹配的子串）。如果  <em>group</em> 存在，但未产生匹配，就返回 <code class="docutils literal notranslate"><span class="pre">-1</span></code> 。对于一个匹配对象 <em>m</em>， 和一个未参与匹配的组 <em>g</em> ，组 <em>g</em> (等价于 <code class="docutils literal notranslate"><span class="pre">m.group(g)</span></code>)产生的匹配是</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">m</span><span class="o">.</span><span class="n">string</span><span class="p">[</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(</span><span class="n">g</span><span class="p">):</span><span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">(</span><span class="n">g</span><span class="p">)]</span>
</pre></div>
</div>
<p>注意 <code class="docutils literal notranslate"><span class="pre">m.start(group)</span></code> 将会等于 <code class="docutils literal notranslate"><span class="pre">m.end(group)</span></code> ，如果 <em>group</em> 匹配一个空字符串的话。比如，在 <code class="docutils literal notranslate"><span class="pre">m</span> <span class="pre">=</span> <span class="pre">re.search('b(c?)',</span> <span class="pre">'cba')</span></code> 之后，<code class="docutils literal notranslate"><span class="pre">m.start(0)</span></code> 为 1, <code class="docutils literal notranslate"><span class="pre">m.end(0)</span></code> 为 2, <code class="docutils literal notranslate"><span class="pre">m.start(1)</span></code> 和 <code class="docutils literal notranslate"><span class="pre">m.end(1)</span></code> 都是 2, <code class="docutils literal notranslate"><span class="pre">m.start(2)</span></code> raise 一个 <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> 例外。</p>
<p>这个例子会从email地址中移除掉 <em>remove_this</em></p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">email</span> <span class="o">=</span> <span class="s2">&quot;tony@tiremove_thisger.net&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;remove_this&quot;</span><span class="p">,</span> <span class="n">email</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">email</span><span class="p">[:</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">()]</span> <span class="o">+</span> <span class="n">email</span><span class="p">[</span><span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">():]</span>
<span class="go">&#39;tony@tiger.net&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.Match.span">
<code class="descclassname">Match.</code><code class="descname">span</code><span class="sig-paren">(</span><span class="optional">[</span><em>group</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.Match.span" title="永久链接至目标">¶</a></dt>
<dd><p>对于一个匹配 <em>m</em> ， 返回一个二元组 <code class="docutils literal notranslate"><span class="pre">(m.start(group),</span> <span class="pre">m.end(group))</span></code> 。 注意如果 <em>group</em> 没有在这个匹配中，就返回 <code class="docutils literal notranslate"><span class="pre">(-1,</span> <span class="pre">-1)</span></code> 。<em>group</em> 默认为0，就是整个匹配。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Match.pos">
<code class="descclassname">Match.</code><code class="descname">pos</code><a class="headerlink" href="#re.Match.pos" title="永久链接至目标">¶</a></dt>
<dd><p><em>pos</em> 的值，会传递给 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 或 <a class="reference internal" href="#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> 的方法 a <a class="reference internal" href="#re-objects"><span class="std std-ref">正则对象</span></a> 。这个是正则引擎开始在字符串搜索一个匹配的索引位置。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Match.endpos">
<code class="descclassname">Match.</code><code class="descname">endpos</code><a class="headerlink" href="#re.Match.endpos" title="永久链接至目标">¶</a></dt>
<dd><p><em>endpos</em> 的值，会传递给 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 或 <a class="reference internal" href="#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> 的方法 a <a class="reference internal" href="#re-objects"><span class="std std-ref">正则对象</span></a> 。这个是正则引擎停止在字符串搜索一个匹配的索引位置。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Match.lastindex">
<code class="descclassname">Match.</code><code class="descname">lastindex</code><a class="headerlink" href="#re.Match.lastindex" title="永久链接至目标">¶</a></dt>
<dd><p>捕获组的最后一个匹配的整数索引值，或者 <code class="docutils literal notranslate"><span class="pre">None</span></code> 如果没有匹配产生的话。比如，对于字符串 <code class="docutils literal notranslate"><span class="pre">'ab'</span></code>，表达式 <code class="docutils literal notranslate"><span class="pre">(a)b</span></code>, <code class="docutils literal notranslate"><span class="pre">((a)(b))</span></code>, 和 <code class="docutils literal notranslate"><span class="pre">((ab))</span></code> 将得到 <code class="docutils literal notranslate"><span class="pre">lastindex</span> <span class="pre">==</span> <span class="pre">1</span></code> ， 而 <code class="docutils literal notranslate"><span class="pre">(a)(b)</span></code> 会得到 <code class="docutils literal notranslate"><span class="pre">lastindex</span> <span class="pre">==</span> <span class="pre">2</span></code> 。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Match.lastgroup">
<code class="descclassname">Match.</code><code class="descname">lastgroup</code><a class="headerlink" href="#re.Match.lastgroup" title="永久链接至目标">¶</a></dt>
<dd><p>最后一个匹配的命名组名字，或者 <code class="docutils literal notranslate"><span class="pre">None</span></code> 如果没有产生匹配的话。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Match.re">
<code class="descclassname">Match.</code><code class="descname">re</code><a class="headerlink" href="#re.Match.re" title="永久链接至目标">¶</a></dt>
<dd><p>返回产生这个实例的 <a class="reference internal" href="#re-objects"><span class="std std-ref">正则对象</span></a> ， 这个实例是由 正则对象的 <a class="reference internal" href="#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> 或 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 方法产生的。</p>
</dd></dl>

<dl class="attribute">
<dt id="re.Match.string">
<code class="descclassname">Match.</code><code class="descname">string</code><a class="headerlink" href="#re.Match.string" title="永久链接至目标">¶</a></dt>
<dd><p>传递到 <a class="reference internal" href="#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> 或 <a class="reference internal" href="#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> 的字符串。</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>添加了对 <a class="reference internal" href="copy.html#copy.copy" title="copy.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.copy()</span></code></a> 和 <a class="reference internal" href="copy.html#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.deepcopy()</span></code></a> 的支持。匹配对象被看作是原子性的。</p>
</div>
</div>
<div class="section" id="regular-expression-examples">
<span id="re-examples"></span><h2>正则表达式例子<a class="headerlink" href="#regular-expression-examples" title="永久链接至标题">¶</a></h2>
<div class="section" id="checking-for-a-pair">
<h3>检查对子<a class="headerlink" href="#checking-for-a-pair" title="永久链接至标题">¶</a></h3>
<p>在这个例子里，我们使用以下辅助函数来更好的显示匹配对象：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">displaymatch</span><span class="p">(</span><span class="n">match</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">match</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="bp">None</span>
    <span class="k">return</span> <span class="s1">&#39;&lt;Match: </span><span class="si">%r</span><span class="s1">, groups=</span><span class="si">%r</span><span class="s1">&gt;&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">(),</span> <span class="n">match</span><span class="o">.</span><span class="n">groups</span><span class="p">())</span>
</pre></div>
</div>
<p>假设你在写一个扑克程序，一个玩家的一手牌为五个字符的串，每个字符表示一张牌，&quot;a&quot; 就是 A, &quot;k&quot;  K， &quot;q&quot;  Q, &quot;j&quot; J, &quot;t&quot; 为 10, &quot;2&quot; 到 &quot;9&quot; 表示2 到 9。</p>
<p>要看给定的字符串是否有效，我们可以按照以下步骤</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">valid</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;^[a2-9tjqk]</span><span class="si">{5}</span><span class="s2">$&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;akt5q&quot;</span><span class="p">))</span>  <span class="c1"># Valid.</span>
<span class="go">&quot;&lt;Match: &#39;akt5q&#39;, groups=()&gt;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;akt5e&quot;</span><span class="p">))</span>  <span class="c1"># Invalid.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;akt&quot;</span><span class="p">))</span>    <span class="c1"># Invalid.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;727ak&quot;</span><span class="p">))</span>  <span class="c1"># Valid.</span>
<span class="go">&quot;&lt;Match: &#39;727ak&#39;, groups=()&gt;&quot;</span>
</pre></div>
</div>
<p>最后一手牌，<code class="docutils literal notranslate"><span class="pre">&quot;727ak&quot;</span></code> ，包含了一个对子，或者两张同样数值的牌。要用正则表达式匹配它，应该使用向后引用如下</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;.*(.).*\1&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;717ak&quot;</span><span class="p">))</span>     <span class="c1"># Pair of 7s.</span>
<span class="go">&quot;&lt;Match: &#39;717&#39;, groups=(&#39;7&#39;,)&gt;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;718ak&quot;</span><span class="p">))</span>     <span class="c1"># No pairs.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;354aa&quot;</span><span class="p">))</span>     <span class="c1"># Pair of aces.</span>
<span class="go">&quot;&lt;Match: &#39;354aa&#39;, groups=(&#39;a&#39;,)&gt;&quot;</span>
</pre></div>
</div>
<p>要找到对子包含的是哪一张牌，应该按照下面的方式使用 <a class="reference internal" href="#re.Match.group" title="re.Match.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a> 方法:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;717ak&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;7&#39;</span>

<span class="go"># Error because re.match() returns None, which doesn&#39;t have a group() method:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;718ak&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#23&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
    <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;.*(.).*\1&quot;</span><span class="p">,</span> <span class="s2">&quot;718ak&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;NoneType&#39; object has no attribute &#39;group&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;354aa&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;a&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="simulating-scanf">
<h3>模拟 scanf()<a class="headerlink" href="#simulating-scanf" title="永久链接至标题">¶</a></h3>
<p id="index-38">Python 目前没有一个类似c函数 <code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> 的替代品。正则表达式通常比 <code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> 格式字符串要更强大一些，但也带来更多复杂性。下面的表格提供了 <code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> 格式符和正则表达式大致相同的映射。</p>
<table border="1" class="docutils">
<colgroup>
<col width="42%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head"><code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> 格式符</th>
<th class="head">正则表达式</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%c</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">.</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%5c</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">.{5}</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%d</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?\d+</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%e</span></code>, <code class="docutils literal notranslate"><span class="pre">%E</span></code>, <code class="docutils literal notranslate"><span class="pre">%f</span></code>, <code class="docutils literal notranslate"><span class="pre">%g</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%i</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%o</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?[0-7]+</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%s</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">\S+</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%u</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">\d+</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%x</span></code>, <code class="docutils literal notranslate"><span class="pre">%X</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?(0[xX])?[\dA-Fa-f]+</span></code></td>
</tr>
</tbody>
</table>
<p>从文件名和数字提取字符串</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">sbin</span><span class="o">/</span><span class="n">sendmail</span> <span class="o">-</span> <span class="mi">0</span> <span class="n">errors</span><span class="p">,</span> <span class="mi">4</span> <span class="n">warnings</span>
</pre></div>
</div>
<p>你可以使用 <code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> 格式化</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="n">d</span> <span class="n">errors</span><span class="p">,</span> <span class="o">%</span><span class="n">d</span> <span class="n">warnings</span>
</pre></div>
</div>
<p>等价的正则表达式是：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">(</span>\<span class="n">S</span><span class="o">+</span><span class="p">)</span> <span class="o">-</span> <span class="p">(</span>\<span class="n">d</span><span class="o">+</span><span class="p">)</span> <span class="n">errors</span><span class="p">,</span> <span class="p">(</span>\<span class="n">d</span><span class="o">+</span><span class="p">)</span> <span class="n">warnings</span>
</pre></div>
</div>
</div>
<div class="section" id="search-vs-match">
<span id="id3"></span><h3>search() vs. match()<a class="headerlink" href="#search-vs-match" title="永久链接至标题">¶</a></h3>
<p>Python 提供了两种不同的操作：基于 <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a> 检查字符串开头，或者 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a> 检查字符串的任意位置（默认Perl中的行为）。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>    <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>   <span class="c1"># Match</span>
<span class="go">&lt;re.Match object; span=(2, 3), match=&#39;c&#39;&gt;</span>
</pre></div>
</div>
<p>在 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> 中，可以用 <code class="docutils literal notranslate"><span class="pre">'^'</span></code> 作为开始来限制匹配到字符串的首位</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>    <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;^c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>  <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;^a&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>  <span class="c1"># Match</span>
<span class="go">&lt;re.Match object; span=(0, 1), match=&#39;a&#39;&gt;</span>
</pre></div>
</div>
<p>注意 <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> 多行模式中函数 <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a> 只匹配字符串的开始，但使用 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> 和以 <code class="docutils literal notranslate"><span class="pre">'^'</span></code> 开始的正则表达式会匹配每行的开始</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;X&#39;</span><span class="p">,</span> <span class="s1">&#39;A</span><span class="se">\n</span><span class="s1">B</span><span class="se">\n</span><span class="s1">X&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">MULTILINE</span><span class="p">)</span>  <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;^X&#39;</span><span class="p">,</span> <span class="s1">&#39;A</span><span class="se">\n</span><span class="s1">B</span><span class="se">\n</span><span class="s1">X&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">MULTILINE</span><span class="p">)</span>  <span class="c1"># Match</span>
<span class="go">&lt;re.Match object; span=(4, 5), match=&#39;X&#39;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="making-a-phonebook">
<h3>建立一个电话本<a class="headerlink" href="#making-a-phonebook" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a> 将字符串用参数传递的样式分隔开。这个方法对于转换文本数据到易读而且容易修改的数据结构，是很有用的，如下面的例子证明。</p>
<p>首先，这里是输入。通常是一个文件，这里我们用三引号字符串语法</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Ross McFluff: 834.345.1254 155 Elm Street</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">Ronald Heathmore: 892.345.3428 436 Finley Avenue</span>
<span class="gp">... </span><span class="s2">Frank Burger: 925.541.7625 662 South Dogwood Way</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">Heather Albrecht: 548.326.4584 919 Park Place&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>条目用一个或者多个换行符分开。现在我们将字符串转换为一个列表，每个非空行都有一个条目:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">entries</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">+&quot;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entries</span>
<span class="go">[&#39;Ross McFluff: 834.345.1254 155 Elm Street&#39;,</span>
<span class="go">&#39;Ronald Heathmore: 892.345.3428 436 Finley Avenue&#39;,</span>
<span class="go">&#39;Frank Burger: 925.541.7625 662 South Dogwood Way&#39;,</span>
<span class="go">&#39;Heather Albrecht: 548.326.4584 919 Park Place&#39;]</span>
</pre></div>
</div>
<p>最终，将每个条目分割为一个由名字、姓氏、电话号码和地址组成的列表。我们为 <a class="reference internal" href="#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a> 使用了 <code class="docutils literal notranslate"><span class="pre">maxsplit</span></code> 形参，因为地址中包含有被我们作为分割模式的空格符:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;:? &quot;</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">entries</span><span class="p">]</span>
<span class="go">[[&#39;Ross&#39;, &#39;McFluff&#39;, &#39;834.345.1254&#39;, &#39;155 Elm Street&#39;],</span>
<span class="go">[&#39;Ronald&#39;, &#39;Heathmore&#39;, &#39;892.345.3428&#39;, &#39;436 Finley Avenue&#39;],</span>
<span class="go">[&#39;Frank&#39;, &#39;Burger&#39;, &#39;925.541.7625&#39;, &#39;662 South Dogwood Way&#39;],</span>
<span class="go">[&#39;Heather&#39;, &#39;Albrecht&#39;, &#39;548.326.4584&#39;, &#39;919 Park Place&#39;]]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">:?</span></code> 样式匹配姓后面的冒号，因此它不出现在结果列表中。如果 <code class="docutils literal notranslate"><span class="pre">maxsplit</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">4</span></code> ，我们还可以从地址中获取到房间号:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;:? &quot;</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">entries</span><span class="p">]</span>
<span class="go">[[&#39;Ross&#39;, &#39;McFluff&#39;, &#39;834.345.1254&#39;, &#39;155&#39;, &#39;Elm Street&#39;],</span>
<span class="go">[&#39;Ronald&#39;, &#39;Heathmore&#39;, &#39;892.345.3428&#39;, &#39;436&#39;, &#39;Finley Avenue&#39;],</span>
<span class="go">[&#39;Frank&#39;, &#39;Burger&#39;, &#39;925.541.7625&#39;, &#39;662&#39;, &#39;South Dogwood Way&#39;],</span>
<span class="go">[&#39;Heather&#39;, &#39;Albrecht&#39;, &#39;548.326.4584&#39;, &#39;919&#39;, &#39;Park Place&#39;]]</span>
</pre></div>
</div>
</div>
<div class="section" id="text-munging">
<h3>文字整理<a class="headerlink" href="#text-munging" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> 替换字符串中出现的样式的每一个实例。这个例子证明了使用  <a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> 来整理文字，或者随机化每个字符的位置，除了首位和末尾字符</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">repl</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">inner_word</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="gp">... </span>    <span class="n">random</span><span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="n">inner_word</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">inner_word</span><span class="p">)</span> <span class="o">+</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;Professor Abdolmalek, please report your absences promptly.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\w)(\w+)(\w)&quot;</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">&#39;Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\w)(\w+)(\w)&quot;</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">&#39;Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="finding-all-adverbs">
<h3>找到所有副词<a class="headerlink" href="#finding-all-adverbs" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a> 匹配样式 <em>所有</em> 的出现，不仅是像 <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> 中的第一个匹配。比如，如果一个作者希望找到文字中的所有副词，他可能会按照以下方法用 <a class="reference internal" href="#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a></p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;He was carefully disguised but captured quickly by police.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\w+ly&quot;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">[&#39;carefully&#39;, &#39;quickly&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="finding-all-adverbs-and-their-positions">
<h3>找到所有副词和位置<a class="headerlink" href="#finding-all-adverbs-and-their-positions" title="永久链接至标题">¶</a></h3>
<p>如果需要匹配样式的更多信息， <a class="reference internal" href="#re.finditer" title="re.finditer"><code class="xref py py-func docutils literal notranslate"><span class="pre">finditer()</span></code></a> 可以起到作用，它提供了 <a class="reference internal" href="#match-objects"><span class="std std-ref">匹配对象</span></a> 作为返回值，而不是字符串。继续上面的例子，如果一个作者希望找到所有副词和它的位置，可以按照下面方法使用 <a class="reference internal" href="#re.finditer" title="re.finditer"><code class="xref py py-func docutils literal notranslate"><span class="pre">finditer()</span></code></a></p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;He was carefully disguised but captured quickly by police.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">re</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\w+ly&quot;</span><span class="p">,</span> <span class="n">text</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%02d</span><span class="s1">-</span><span class="si">%02d</span><span class="s1">: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)))</span>
<span class="go">07-16: carefully</span>
<span class="go">40-47: quickly</span>
</pre></div>
</div>
</div>
<div class="section" id="raw-string-notation">
<h3>原始字符记法<a class="headerlink" href="#raw-string-notation" title="永久链接至标题">¶</a></h3>
<p>原始字符串记法 (<code class="docutils literal notranslate"><span class="pre">r&quot;text&quot;</span></code>) 保持正则表达式正常。否则，每个正则式里的反斜杠(<code class="docutils literal notranslate"><span class="pre">'\'</span></code>) 都必须前缀一个反斜杠来转义。比如，下面两行代码功能就是完全一致的</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\W(.)\1\W&quot;</span><span class="p">,</span> <span class="s2">&quot; ff &quot;</span><span class="p">)</span>
<span class="go">&lt;re.Match object; span=(0, 4), match=&#39; ff &#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">W(.)</span><span class="se">\\</span><span class="s2">1</span><span class="se">\\</span><span class="s2">W&quot;</span><span class="p">,</span> <span class="s2">&quot; ff &quot;</span><span class="p">)</span>
<span class="go">&lt;re.Match object; span=(0, 4), match=&#39; ff &#39;&gt;</span>
</pre></div>
</div>
<p>当需要匹配一个字符反斜杠，它必须在正则表达式中转义。在原始字符串记法，就是 <code class="docutils literal notranslate"><span class="pre">r&quot;\\&quot;</span></code>。否则就必须用 <code class="docutils literal notranslate"><span class="pre">&quot;\\\\&quot;</span></code>，来表示同样的意思</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span><span class="p">,</span> <span class="sa">r</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="go">&lt;re.Match object; span=(0, 1), match=&#39;\\&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\\\\</span><span class="s2">&quot;</span><span class="p">,</span> <span class="sa">r</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="go">&lt;re.Match object; span=(0, 1), match=&#39;\\&#39;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="writing-a-tokenizer">
<h3>写一个词法分析器<a class="headerlink" href="#writing-a-tokenizer" title="永久链接至标题">¶</a></h3>
<p>一个 <a class="reference external" href="https://en.wikipedia.org/wiki/Lexical_analysis">词法器或词法分析器</a> 分析字符串，并分类成目录组。 这是写一个编译器或解释器的第一步。</p>
<p>文字目录是由正则表达式指定的。这个技术是通过将这些样式合并为一个主正则式，并且循环匹配来实现的</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">collections</span>
<span class="kn">import</span> <span class="nn">re</span>

<span class="n">Token</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Token&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;type&#39;</span><span class="p">,</span> <span class="s1">&#39;value&#39;</span><span class="p">,</span> <span class="s1">&#39;line&#39;</span><span class="p">,</span> <span class="s1">&#39;column&#39;</span><span class="p">])</span>

<span class="k">def</span> <span class="nf">tokenize</span><span class="p">(</span><span class="n">code</span><span class="p">):</span>
    <span class="n">keywords</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;IF&#39;</span><span class="p">,</span> <span class="s1">&#39;THEN&#39;</span><span class="p">,</span> <span class="s1">&#39;ENDIF&#39;</span><span class="p">,</span> <span class="s1">&#39;FOR&#39;</span><span class="p">,</span> <span class="s1">&#39;NEXT&#39;</span><span class="p">,</span> <span class="s1">&#39;GOSUB&#39;</span><span class="p">,</span> <span class="s1">&#39;RETURN&#39;</span><span class="p">}</span>
    <span class="n">token_specification</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="s1">&#39;NUMBER&#39;</span><span class="p">,</span>   <span class="sa">r</span><span class="s1">&#39;\d+(\.\d*)?&#39;</span><span class="p">),</span>  <span class="c1"># Integer or decimal number</span>
        <span class="p">(</span><span class="s1">&#39;ASSIGN&#39;</span><span class="p">,</span>   <span class="sa">r</span><span class="s1">&#39;:=&#39;</span><span class="p">),</span>           <span class="c1"># Assignment operator</span>
        <span class="p">(</span><span class="s1">&#39;END&#39;</span><span class="p">,</span>      <span class="sa">r</span><span class="s1">&#39;;&#39;</span><span class="p">),</span>            <span class="c1"># Statement terminator</span>
        <span class="p">(</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span>       <span class="sa">r</span><span class="s1">&#39;[A-Za-z]+&#39;</span><span class="p">),</span>    <span class="c1"># Identifiers</span>
        <span class="p">(</span><span class="s1">&#39;OP&#39;</span><span class="p">,</span>       <span class="sa">r</span><span class="s1">&#39;[+\-*/]&#39;</span><span class="p">),</span>      <span class="c1"># Arithmetic operators</span>
        <span class="p">(</span><span class="s1">&#39;NEWLINE&#39;</span><span class="p">,</span>  <span class="sa">r</span><span class="s1">&#39;\n&#39;</span><span class="p">),</span>           <span class="c1"># Line endings</span>
        <span class="p">(</span><span class="s1">&#39;SKIP&#39;</span><span class="p">,</span>     <span class="sa">r</span><span class="s1">&#39;[ \t]+&#39;</span><span class="p">),</span>       <span class="c1"># Skip over spaces and tabs</span>
        <span class="p">(</span><span class="s1">&#39;MISMATCH&#39;</span><span class="p">,</span> <span class="sa">r</span><span class="s1">&#39;.&#39;</span><span class="p">),</span>            <span class="c1"># Any other character</span>
    <span class="p">]</span>
    <span class="n">tok_regex</span> <span class="o">=</span> <span class="s1">&#39;|&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s1">&#39;(?P&lt;</span><span class="si">%s</span><span class="s1">&gt;</span><span class="si">%s</span><span class="s1">)&#39;</span> <span class="o">%</span> <span class="n">pair</span> <span class="k">for</span> <span class="n">pair</span> <span class="ow">in</span> <span class="n">token_specification</span><span class="p">)</span>
    <span class="n">line_num</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="n">line_start</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">mo</span> <span class="ow">in</span> <span class="n">re</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="n">tok_regex</span><span class="p">,</span> <span class="n">code</span><span class="p">):</span>
        <span class="n">kind</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">lastgroup</span>
        <span class="n">value</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
        <span class="n">column</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="o">-</span> <span class="n">line_start</span>
        <span class="k">if</span> <span class="n">kind</span> <span class="o">==</span> <span class="s1">&#39;NUMBER&#39;</span><span class="p">:</span>
            <span class="n">value</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="k">if</span> <span class="s1">&#39;.&#39;</span> <span class="ow">in</span> <span class="n">value</span> <span class="k">else</span> <span class="nb">int</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">kind</span> <span class="o">==</span> <span class="s1">&#39;ID&#39;</span> <span class="ow">and</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">keywords</span><span class="p">:</span>
            <span class="n">kind</span> <span class="o">=</span> <span class="n">value</span>
        <span class="k">elif</span> <span class="n">kind</span> <span class="o">==</span> <span class="s1">&#39;NEWLINE&#39;</span><span class="p">:</span>
            <span class="n">line_start</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">end</span><span class="p">()</span>
            <span class="n">line_num</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="k">continue</span>
        <span class="k">elif</span> <span class="n">kind</span> <span class="o">==</span> <span class="s1">&#39;SKIP&#39;</span><span class="p">:</span>
            <span class="k">continue</span>
        <span class="k">elif</span> <span class="n">kind</span> <span class="o">==</span> <span class="s1">&#39;MISMATCH&#39;</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;</span><span class="si">{value!r}</span><span class="s1"> unexpected on line </span><span class="si">{line_num}</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="k">yield</span> <span class="n">Token</span><span class="p">(</span><span class="n">kind</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">line_num</span><span class="p">,</span> <span class="n">column</span><span class="p">)</span>

<span class="n">statements</span> <span class="o">=</span> <span class="s1">&#39;&#39;&#39;</span>
<span class="s1">    IF quantity THEN</span>
<span class="s1">        total := total + price * quantity;</span>
<span class="s1">        tax := price * 0.05;</span>
<span class="s1">    ENDIF;</span>
<span class="s1">&#39;&#39;&#39;</span>

<span class="k">for</span> <span class="n">token</span> <span class="ow">in</span> <span class="n">tokenize</span><span class="p">(</span><span class="n">statements</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>
</pre></div>
</div>
<p>这个词法器产生以下输出</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;IF&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;IF&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;quantity&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">7</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;THEN&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;THEN&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">16</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;total&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ASSIGN&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;:=&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;total&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">17</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;OP&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">23</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;price&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">25</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;OP&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">31</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;quantity&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">33</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;END&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;;&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">41</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;tax&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ASSIGN&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;:=&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">12</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ID&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;price&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;OP&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">21</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;NUMBER&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="mf">0.05</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">23</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;END&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;;&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">27</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;ENDIF&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;ENDIF&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="s1">&#39;END&#39;</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s1">&#39;;&#39;</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">9</span><span class="p">)</span>
</pre></div>
</div>
<table class="docutils citation" frame="void" id="frie09" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[Frie09]</a></td><td>Friedl, Jeffrey. Mastering Regular Expressions. 第三版, O’Reilly Media, 2009. 第三版不再使用Python, 但第一版提供了编写正则表达式的良好细节。</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="docutils literal notranslate"><span class="pre">re</span></code> --- 正则表达式操作</a><ul>
<li><a class="reference internal" href="#regular-expression-syntax">正则表达式语法</a></li>
<li><a class="reference internal" href="#module-contents">模块内容</a></li>
<li><a class="reference internal" href="#regular-expression-objects">正则表达式对象 （正则对象）</a></li>
<li><a class="reference internal" href="#match-objects">匹配对象</a></li>
<li><a class="reference internal" href="#regular-expression-examples">正则表达式例子</a><ul>
<li><a class="reference internal" href="#checking-for-a-pair">检查对子</a></li>
<li><a class="reference internal" href="#simulating-scanf">模拟 scanf()</a></li>
<li><a class="reference internal" href="#search-vs-match">search() vs. match()</a></li>
<li><a class="reference internal" href="#making-a-phonebook">建立一个电话本</a></li>
<li><a class="reference internal" href="#text-munging">文字整理</a></li>
<li><a class="reference internal" href="#finding-all-adverbs">找到所有副词</a></li>
<li><a class="reference internal" href="#finding-all-adverbs-and-their-positions">找到所有副词和位置</a></li>
<li><a class="reference internal" href="#raw-string-notation">原始字符记法</a></li>
<li><a class="reference internal" href="#writing-a-tokenizer">写一个词法分析器</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="string.html"
                        title="上一章"><code class="docutils literal notranslate"><span class="pre">string</span></code> --- 常见的字符串操作</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="difflib.html"
                        title="下一章">模块 <cite>difflib</cite>  是一个计算差异的助手</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/re.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="difflib.html" title="模块 difflib 是一个计算差异的助手"
             >下一页</a> |</li>
        <li class="right" >
          <a href="string.html" title="string --- 常见的字符串操作"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">zh_CN</span>
          <span class="version_switcher_placeholder">3.7.3</span>
          <a href="../index.html">文档</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="text.html" >文本处理服务</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2019, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 4月 09, 2019.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>1.8.4 创建。
    </div>

  </body>
</html>